2013-06-01 69 views
1

我有一个结构数组,每个结构都作为元素列表工作。 我需要添加多个对象到每个结构和我的添加功能它不能正常工作。C:添加和删除结构数组中的元素

这是结构:

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; 
} 

我还需要删除书本功能,但我想先解决此问题。 谢谢你的建议。

+0

究竟是什么问题?发生什么事?你是否使用调试器来理解? –

+1

马上我可以告诉你这一点:在你的对象结构中,字段'next'应该是'list *'类型(指向列表的指针)。 – djf

+0

问题是,如何将多个数据添加到每个结构中的列表中。 – Kibz

回答

0

什么是错误信息?

在你的代码:

p->next = p; 

似乎应该是:

aux->next = p; 

这样一来,你插入一个产品作为列表的头部。

+0

我没有收到任何错误消息,但是当我打印[0] [0]里的所有数组时,它是空的。我认为问题在于它指向别处的函数中的'p'指针。 – Kibz

0

2个问题我看到的是

p->next = p; -> aux->next = p; 

//if 
    p=&t[0][0]; 

    then 

    at the end 

    t[0][0] = p; 

因为我觉得T [0] [0]仍然指向更早指针,而不是指向列表的开始所以添加节点不可见