Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A warning I don't understand using malloc() in C language

This is some code I wrote to exercise using malloc(). In particular, I want to have a char-array of dimension and elements given by the user and to print these elements.

#include <stdio.h>
#include <stdlib.h>

int main() {

    char *ptr;
    int d;
    
    printf("Inserire la dimensione dell'array CHAR:\n");
    scanf("%d", &d);
    
    ptr = (char *) malloc(d * sizeof(char));
    
    for (int i = 0; i < d; i++) {
    
        printf("Inserire un char:\n");
        scanf("%c", ptr[i]);
    
    }
    
    for (int j = 0; j < d; j++) {
    
        printf("%c", ptr[j]);
    
    }
    
    return 0;

}

The compiler gives a warning at line 17: warning: fomat "%c" expects argument of type "char", but argument 2 has type "int". I tried previously scanf("%c", &ptr[i]) at line 17 which to me seems also more natural, but the code runs badly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

&ptr[i] is the correct way, at least it does something, even though that something is wrong. The alternative (ptr[i]) does nothing (or even worse it is Undefined Behavior, which programmers should avoid in their code). The reason why the first code runs badly is because you must type Enter after you enter the character. The second scanf will read that Enter. To "consume" this Enter and any other white-space character (and also the Enter that you type when entering the length of the array) just add one space in scanf format:

scanf(" %c", &ptr[i]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading