【发布时间】:2020-10-10 20:19:58
【问题描述】:
我试图弄清楚如何将输入文件中的值存储到指向结构的指针数组中。输入文件如下所示(首先是结构中的名称,后面的数字将存储到结构中的整数数组中)。中间的打印语句是为了帮助我查看程序失败的地方。
我的代码:
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() 的目标位置是否错误,因为它是指向结构的指针数组?这是我唯一能想到但不知道如何正确执行的事情。
【问题讨论】:
-
虽然打印可以作为一个指标,但我建议尝试使用调试器,因为它可以提供更多信息,而另一种可能在这种情况下有效的工具可能是 valgrind。