【发布时间】:2012-03-25 14:26:07
【问题描述】:
我已经尝试了好几个小时才能让这个功能正常工作。这是作业:
添加:请求零件名称、价格和数量。将信息保存到动态分配的结构数组中。您一次最多可以为 3 个结构分配空间。您将需要根据需要动态创建更多内存。使用这个结构(如果你愿意,你可以使用 typedef):
到目前为止,我拥有的代码是
typedef struct {
char* name;
float price;
int quantity;
}part;
void add(part *item, int *part_count)
{
//char temp[100];
if (!item){
item = malloc(sizeof(part)*3);
}
else{
item = realloc(item, sizeof(part) * ((*part_count*3) + 1));
}
item[*part_count].name = malloc(sizeof(char)*64); // max of 64 characters
printf("Please enter item name: \n");
//fgets(temp, strlen(temp), stdin);
//sscanf(temp, "%s", item[*part_count].name);
scanf("%64s", item[*part_count].name);
printf("Please enter item price: \n");
//fgets(temp, strlen(temp), stdin);
//sscanf(temp, "%f", &item[*part_count].price);
scanf("%f", &item[*part_count].price);
printf("Please enter item quantity: \n");
//fgets(temp, strlen(temp), stdin);
//sscanf(temp, "%d", &item[*part_count].quantity);
scanf("%d", &item[*part_count].quantity);
*part_count = *part_count+ 1;
}
我曾尝试使用fgets() 和sscanf() 进行输入,但使用该代码时,它不允许用户输入数据然后结束函数。
我认为问题在于我的内存分配,因为当我尝试对数组执行任何操作(例如打印出内容)时出现分段错误。
【问题讨论】:
-
您在哪条线路上遇到了段错误?
-
你如何计算
part_count?如果是元素的数量,则无法访问该元素。因此,如果您的数组大小为10,则无法访问array[10]。 -
我不确定哪一行出现了段错误,但我有一个单独的打印功能,当我运行它时它会出现段错误。我以前问过,但显然我的打印功能不是问题。 part_count 也从 0 开始,每次调用 add 时递增。
-
如何检查 seg 故障的位置?
-
@TristanPearce:你可以使用 gdb。这是short tutorial