将值存储到结构指针的数组

问题描述

我试图弄清楚如何将输入文件中的值存储到指向结构的指针数组中。输入文件如下所示(第一个是结构体中的名称,以下数字将存储到结构体中的整数数组中)。中间的打印语句可以帮助我查看程序在哪里失败。

我的代码

typedef struct{
  char name[10];
  int songs[10];
}Customer;

Customer *memory_locations[100];

int main(int argc,char* argv[])
{

  FILE *fp_data = fopen(argv[1],"r"); //file with tree structure
  FILE *fp_query = fopen(argv[2],"r"); //file with commands


  int index = 0;
  char targetCust[10];
  char buffer;

  fscanf(fp_data,"%s\n",targetCust);

  while(!feof(fp_data)){
    printf("1%d",index);
    memory_locations[index] = (Customer *)malloc(sizeof(Customer));
    printf("2%d",index);
    fscanf(fp_data,"%s",memory_locations[index]->name);
    printf("3%d",index);
    for(int i = 0; i<10; i++){
      fscanf(fp_data," %d",memory_locations[index]->songs[i]);
      printf("4%d",index);
    }
    printf("5%d",index);
    index++;
  }

  printf("%d %s",index,targetCust);
  
}

输入文件

Alice
Alice 4 2 0 2 0 0 5 3 3 2
Bob   0 0 1 2 0 3 5 1 1 5
Carol 0 2 0 0 2 1 0 1 1 2
David 2 2 0 2 1 2 3 1 3 0
Emily 0 4 0 2 5 5 4 3 0 3

输出返回102030,然后出现分段错误,因此问题是从输入文件中读取整数。 fscanf()的目标位置是否错误,因为它是指向结构的指针数组?这是我唯一能想到的,却不知道如何正确执行。

解决方法

fscanf()中的目标位置是否错误,因为它是指向结构的指针数组?

否,fscanf是错误的,因为程序中有一个小的错字。 fscanf需要参数中的指针。其余代码似乎还可以。

fscanf(fp_data," %d",memory_locations[index]->songs[i]); // Segfault
fscanf(fp_data,&memory_locations[index]->songs[i]); // Correct
                       ^

对于name来说,没有问题,因为memory_locations[index]->name对应于表开头的地址。