【问题标题】:fgets() weird behavior with realloc()fgets() realloc() 的奇怪行为
【发布时间】: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 扫描该行以查找数字@。最好不要混用fgetsscanf

标签: c string dynamic-memory-allocation fgets realloc


【解决方案1】:

主要问题在这里:

temp[strspn(temp, "\n")] = '\0';

您使用了错误的功能。你想要strcspn,而不是strspn。将其更改为:

temp[strcspn(temp, "\n")] = '\0';

另外,正如其他人指出的那样,您不应该更改 howMany 的值,因为您需要在循环中使用它的原始值。

【讨论】:

  • @Martin R "或strchr(temp, '\n')" 缺少上下文。像*strchr(temp, '\n') = '\0'; 这样的错误使用是黑客利用的开始。正确使用:{ char *p = strchr(temp, '\n'); if (p) *p = '\0';}
猜你喜欢
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多