【问题标题】:Why does sscanf reads only two lines with pointer to pointer?为什么 sscanf 只读取两行带有指针的指针?
【发布时间】:2020-11-22 15:49:39
【问题描述】:

我有一个有 10 行的文件,每行有一个名称、一个 ID 和一个年龄,用空格分隔。问题是当使用 fgets 和 sscanf 读取这个文件时,它会在尝试读取超过 2 行时返回一个 seg 错误。

typedef struct Person
{
    char t;
    long i;
    float a;
} Person;



*arrPersons = (Person*)malloc(10 * sizeof(Person));

int assignInputPeople(Person **arrPersons,  FILE *inputPeople)
{
    int counter = 0;
    char fileLine[344];
    long ID;
float ageF;
 while (fgets(fileLine, 344, inputPeople) != NULL)
    {
        sscanf(fileLine, "%s %s %s", arrPersons[counter]->name,&ID)
   
    
}

我为我的数组创建了一个指向指针的指针,以便我可以在其他函数中修改它,例如上面的这个。

【问题讨论】:

标签: arrays c pointers scanf


【解决方案1】:

如果您在main() 函数中将arrPersons 的地址作为assignInputPeople() 函数的参数arrPersons 传递,则arrPersons[counter]->name 是错误的,因为arrPersons 指向的内容只有空间一个elemnet,所以当counter 不是0 时它超出范围。

在这种情况下,应该是(*arrPersons)[counter].name。

【讨论】:

  • *arrPersons = (Person*)malloc(10 * sizeof(Person)) 这行实际上在哪里?
  • 还有capacity是什么?
  • 你知道为什么我有一个警告说我的字段没有在我的结构中使用吗?
  • 应该是你的字段没有被使用。
  • 但是在使用 sscanf 时,我使用它们来将数据存储在行中,例如 for (*arrPersons)[counter].id ,或者它不算被访问?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2017-09-21
  • 2022-07-14
相关资源
最近更新 更多