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.
&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]);