谁能给我解释一下,为什么这段代码不能工作。我看了看周围的一些问题,但没有找到答案。可能是因为(巨大的)知识匮乏。
感谢您的帮助。
char** sentence = malloc(min);
char* temp = malloc(min2);
int i = 0;
while(i<5)
{
sentence = realloc(sentence, i+2);
scanf("%s", temp);
sentence[i] = malloc(strlen(temp));
strcpy(sentence[i], temp);
printf("%s\n", sentence[i]);
i++;
}发布于 2012-03-08 08:17:45
您忘记了字符串有空终止符的事实。
发布于 2012-03-08 08:21:23
sentence[i] = malloc(strlen(temp));应该是:
sentence[i] = malloc(strlen(temp)+1);对于字符串(strlen)的长度,和都需要足够的空间,对于它的空终止符也需要足够的空间。
发布于 2012-03-08 08:24:02
sentence = realloc(sentence, (i+1) * sizeof(*sentence));更有意义的是:您正在尝试存储i+1 char*,而不是i+2字节。
顺便说一下,您可以将malloc/strlen/strcpy替换为:
sentence[i] = strdup(temp);(它会为您处理nul终结器)。
https://stackoverflow.com/questions/9611185
复制相似问题