Hi guys I am a beginner in C, and I have trouble when testing array pointer and allocating dynamic memory.
int x,i=0;
char *myChar;
printf("Please enter the length: ");
scanf("%d",&x);
myChar = (char*)malloc(x*sizeof(char));
printf("Please enter %d characters:",x);
for(i=0;i<x;i++){
scanf("%c ",&myChar[i]);
}
for(i=0;i<x;i++){
printf("%c",myChar[i]);
}
free(myChar);
If I enter 5 for length, and "hello" for character array, I get "hell" instead of "hello", which is not fun. Anybody can help me with this? Thanks
"hello"as a string you need 6 bytes, with the last holding the terminating'\0'. You're storing and accessing individual characters in an array, so you don't need the'\0', but it's a somewhat odd approach.printf("%s", myChar);or use one of the library string functions, it would fail for two reasons. First it has no zero-terminator, and even if you put one after the input loop withmyChar[i]=0;it would fail because the buffer is not big enough unless you didmyChar=malloc(x+1);. And note, your other frills inmalloc()call are uneccessary.