I'm having some trouble understanding a string declaration in C using dynamic memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *putText(){
char *s=(char *) malloc(256+sizeof(char));
for(int i=0; *(s+i); i++) *(s+i)=getchar();
return s;
}
void main(){
printf("Write the text: ");
char *s=putText();
printf("%s", s);
}
In this function, I'm trying to declare the string using getchar()
in a for loop, but when I try to print the string, it always stops at the third character.
I am still a newbie, so I've probably made some mistake. Can someone help?