<分区>
我知道我能做到
char string[100];
gets(string);
但我如何才能动态地为该字符串分配内存,该字符串的长度不一定是 100?
标签 c
<分区>
我知道我能做到
char string[100];
gets(string);
但我如何才能动态地为该字符串分配内存,该字符串的长度不一定是 100?
最佳答案
您可以使用realloc
来获取未知长度的字符串。逐个字符读取输入的字符串,直到找到'\n'
或EOF
,每次使用realloc
为下一个字符分配内存读。
char *read_string(void)
{
int c;
int i = 0;
char *s = malloc(1);
printf("Enter a string: \t"); // It can be of any length
/* Read characters until found an EOF or newline character. */
while((c = getchar()) != '\n' && c != EOF)
{
s[i++] = c;
s = realloc(s, i+1); // Add memory space for another character to be read.
}
s[i] = '\0'; // Nul terminate the string
return s;
}
关于c - 我怎样才能从用户那里得到一个字符串然后动态分配它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37074900/