Ker*_*Ker 3 c string memory-management realloc
我正在学习C编程,我必须实现一个读取未知大小的输入字符串的程序.我写了这段代码:
int main() {
char *string;
char c;
int size = 1;
string = (char*)malloc(sizeof(char));
if (string == NULL) {
printf("Error.\n");
return -1;
}
printf("Enter a string:");
while ((c = getchar()) != '\n') {
*string = c;
string = (char*)realloc(string, sizeof(char) * (size + 1));
size++;
}
string[size - 1] = '\0';
printf("Input string: %s\n", string);
free(string);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是最后一个printf不显示整个字符串而只显示最后一个字符.所以,如果我输入hello, world最后的printf打印件d.
经过一番研究后,我尝试了这段代码,它的确有效!但我并没有与我的差别.
我希望自己清楚明白,谢谢你的关注.
在你的代码的版本,你的新读取字符分配,c以string使用:
*string = c;
Run Code Online (Sandbox Code Playgroud)
*string 指向字符串的开头,以便继续用新读取的字符替换字符串的第一个字符.
您链接的代码执行以下操作:
str[i] = c
Run Code Online (Sandbox Code Playgroud)
基本上,它使用索引将字符分配给字符串的末尾i.
在您的代码版本中,您可以使用size - 1而不是代码i.