What's the way when i want to store string that i don't know the size.
I do like this:
#include <stdio.h>
#include <conio.h>
int main () {
char * str;
str = (char *)malloc(sizeof(char) + 1);
str[1] = '\0';
int i = 0;
int c = '\0';
do {
c = getche();
if(c != '\r'){
str[i] = c;
str[i + 1] = '\0';
i++;
str = (char *)realloc(str, sizeof(char) + i + 2);
}
} while(c != '\r');
printf("\n%s\n", str);
free(str);
return 0;
}
I find this page: Dynamically prompt for string without knowing string size
Is it correct? If it is, then:
Is there any better way?
Is there more efficient way?
conio.his non-standard.malloc()and family in C. Note also thatsizeof (char)is one, by definition, sincesizeofgives its results in units ofchar.do...while()loop, replace all that with a call toreadline(). that function will allocate enough memory from the heap for the whole line, and return a pointer to the allocated area in the heap. (or NULL if the allocation fails)