【发布时间】:2016-07-30 15:36:18
【问题描述】:
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)
预期输出: 丹尼尔 大卫
【问题讨论】:
-
如何不工作?
-
我也很困惑@YuHao
-
不,描述它是如何不工作的,例如,你的输入、预期输出、当前输出等。
-
..如果您在调试器下运行程序会很明显..
-
"howMany in necessary" 不,如果您正确设计输入,则不是这样:扫描名称的数量时,先读取一行,然后使用@987654322 扫描该行以查找数字@。最好不要混用
fgets和scanf。
标签: c string dynamic-memory-allocation fgets realloc