I need to get a string without asking for a length,
I create a buffer of 100 char and when is full I do a realloc to add a space for a char at the end of the string
this is my code…could you help me?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char *content = malloc(10*sizeof(char));
char c;
content[0]='\0';
while ((c = getchar()) != EOF)
{
if (strlen(content) < 10){
strcat(content, &c);
content[strlen(content)+1] = '\0';
}
else {
content=realloc(content,sizeof(char)*(strlen(content))+2);
strcat(content, &c);
content[strlen(content)+1] = '\0';
}
}
printf("%s",content);
return 0;
}
A few issues here:
strcatlike that! You should pass a pointer to a\0terminated string, instead of a pointer to a single char. This only works by accident.strlen().strlen()constantly. Set the terminating\0once, after the loop is done.