gpt4 book ai didi

C:添加和删除结构数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:43 24 4
gpt4 key购买 nike

我有一个结构数组,每个结构都作为一个元素列表。我需要向每个结构添加多个对象,而我的添加函数无法正常工作。

这是结构:

typedef struct object book, *list;
struct object{
int type;
int quantity;
list next;
};

这就是我定义数组的方式以及我在 main() 函数中的内容:

row_n=4 //fixed just for now
cols_n=3

product **t;

t= (product **)calloc(row_n, sizeof(product *)); // array of row pointers
for (int i= 0; i<n; i++) {
t[i]= (product *)calloc(cols_n, sizeof(product)); // array of cols prod structs
}

t[1][1].type= 5; //only for testing
t[1][1].quantity= 15; //only for testing
list_all(t,row_n,col_n); //list all elements inside each array, its working as intended
insert(t, 3, 6); //Trying to insert more books
insert(t, 6, 10);
insert(t, 9, 50);

这是 list_all 函数:

void list_all(product **t , int size_n , int size_m)
{
int i,j;
product *p;

for(i=0;i<size_n;i++){
printf("--- row: ---: %d\n", i+1);
for(j=0;j<size_m;j++){
printf("--- col: ---: %d\n",j+1);
p= &t[i][j];
do {
printf("Book Type:%d Amount:%d\n", p->type, p->quantity);
p= p->next;
} while (p!=NULL);
}
}
}

这就是我的问题所在,我需要修复这个插入函数:

void insert(product **t, int id, int quantity)
{
product *p, *aux = NULL;
p=&t[0][0]; //doing it only in one position to test
if((aux = malloc(sizeof(product))) == NULL)
printf("Memory error\n");
else
{
aux->type=id;
aux->quantity=quantity;
p->next = p; }
p = aux;
}

我也需要一个移除书籍的功能,但我想先解决这个问题。感谢您的建议。

最佳答案

错误信息是什么?

在你的代码中:

p->next = p;

似乎应该是:

aux->next = p;

通过这种方式,您可以将产品作为列表的开头插入。

关于C:添加和删除结构数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16878152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com