I atentionally keep optional details for a best undersanding. say we want to store a string in a variable of char* :
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char * s;
int n;
do{
printf("string's length: ");
scanf("%d", &n);
}while(n<=0);
s = (char *) malloc((n+1) * sizeof(char));
if(s!=NULL){
printf("enter a string (length <= %d): ", n);
gets(s);
puts(s);
free(s);
}
puts("end of programme.\n");
return 0;
}
in this answer it says :
If you were to set s to point to a preexisting array or if you used malloc to allocate space, then you can write to it successfully.
so, despite all that, why the call to gets
still doesn't success? how can we explain this behavior ?