我一直在尝试几个小时才能使该函数正常工作。这里的任务:动态分配的数组结构
Add: Request the part name, price, and quantity. Save the information to a dynamically allocated array of structs. You may allocate space for up to 3 structs at a time. You will need to create more memory dynamically as needed. Use this struct (you may use typedef if you want to):
到目前为止我的代码是
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()
输入,但使用的代码它永远不会允许用户输入数据,然后结束功能。
我相信问题在于我的内存分配,因为当我尝试对数组执行任何操作(例如打印内容)时出现分段错误。
你会得到哪些线路故障? – 2012-03-08 02:13:13
你如何计算'part_count'?如果是元素的数量,则无法访问该元素。所以如果你的数组大小为10,你不能访问array [10]。 – prelic 2012-03-08 02:13:30
我不知道哪条线我得到seg故障,但我有一个单独的打印功能,当它运行时它seg故障。我曾问过,但显然我的打印功能不是问题。 part_count也从0开始,每次调用add时都会增加。 – 2012-03-08 02:20:48