![](/img/trans.png)
[英]C: Weird behavior after calling realloc() when using fgets() to store strings in a dynamic buffer
[英]fgets() weird behavior with realloc()
int main(void)
{
int howMany,i,j;
char* temp = NULL;
char** friends = NULL;
printf("Please enter the number of the friends you have\n");
scanf(" %d",&howMany);
howMany++;
friends = (char**) malloc(sizeof(char*)*howMany);
for (i = 0; i < howMany; i++)
{
temp = (char*) malloc(20*sizeof(char));
fgets(temp,20,stdin);
temp[strspn(temp, "\n")] = '\0';
*(friends + i) = (char*)realloc(temp,sizeof(char) * (strlen(temp)+1));
}
for (i = 0; i < howMany; i++)
{
for ( j = 0; j < strlen(*(friends+i)); j++)
{
printf("%c",friends[i][j]);
}
printf("\n");
}
for (i = 0; i < howMany; i++)
{
free(*(friends + i));
}
free(friends);
getchar();
return 0;
}
我的代码的目的是获得我所拥有的朋友的数量,他们的名字并最终将其打印到屏幕上,我的代码为什么不起作用?
输入:2丹尼尔·大卫
输出:
(\\ n)
预期产量:Daniel David
主要问题在这里:
temp[strspn(temp, "\n")] = '\0';
您使用了错误的功能。 您需要strcspn
,而不是strspn
。 更改为:
temp[strcspn(temp, "\n")] = '\0';
另外,正如其他人指出的那样,您不应更改howMany
的值,因为在循环中需要它的原始值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.