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

Arrays 将值存储到指向结构的指针数组中,arrays,c,pointers,struct,Arrays,C,Pointers,Struct,我试图找出如何将输入文件中的值存储到指向结构的指针数组中。输入文件如下所示(首先是结构中的名称,以下数字将存储到结构中的整数数组中)。中间的print语句可以帮助我看到程序失败的地方 我的代码: typedef struct{ char name[10]; int songs[10]; }Customer; Customer *memory_locations[100]; int main(int argc, char* argv[]) { FILE *fp_data = fo

我试图找出如何将输入文件中的值存储到指向结构的指针数组中。输入文件如下所示(首先是结构中的名称,以下数字将存储到结构中的整数数组中)。中间的print语句可以帮助我看到程序失败的地方

我的代码:

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);
  
}
输出返回102030,然后是分段错误,因此问题是从输入文件读取整数。fscanf()中的目标位置是否错误,因为它是指向结构的指针数组?这是我能想到的唯一一件事,但我不知道如何正确地去做

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

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

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

对于
name
,没有问题,因为
memory\u locations[index]->name
对应于表开头的地址。

虽然打印可能是一个指示器,但我建议尝试使用调试器,因为它可以提供更多信息,在这种情况下,另一种可能有效的工具是valgrind。
fscanf(fp_data, " %d",  memory_locations[index]->songs[i]); // Segfault
fscanf(fp_data, " %d", &memory_locations[index]->songs[i]); // Correct
                       ^