我使用的是一个二维指针数组,每个指针都指向一个产品链接列表。 我想构建一个列出所有列表中所有产品的函数。 这是我的结构:
typedef struct object product, *pprod;
struct object{
int type;
int quantity;
pprod next;
};
这就是我定义数组的方式(它必须是动态的):
n=4;
m=3;
pprod (*t)[m] = malloc(n * sizeof *t);
list_all(t,n,m);
这是显示所有产品的功能:
void list_all(pprod** t , int size_n , int size_m) {
int i,j;
for(i=0;i<size_n;i++){
printf("--- Corridor ---: %d\n", i);
for(j=0;j<size_m;j++){
printf("--- Shelf ---: %d\n",j);
printf("product:%d quantity:%d",t[i][j]->type,t[i][j]->quantity);
}
}
}
我在将数组作为参数传递时遇到问题。你能帮我找出问题所在吗? 谢谢您的帮助。
最佳答案
嗯,首先数组的创建是错误的。您只需将一个大小为 4 的(单个) vector 分配给第 m+1 个元素(t vector ,除非您在其他地方这样做,否则指向随机区域)。
n=4;
m=3;
product **t, *newitem;
t= (product **)calloc(n, sizeof(product *)); // array of n pointers (corridor)
for (int i= 0; i<n; i++) {
t[i]= (product *)calloc(m, sizeof(product)) // array of m prod structs (m shelfs per corridor)
}
// access some array members (t[n][m] max t[0-2][0-3])
t[0][0].type= 0;
t[0][0].quantity= 0;
t[0][1].type= 1;
t[0][1].quantity= 11;
...
t[1][2].type= 12;
t[1][2].quantity= 1212;
....
t[2][3].type= 23;
t[2][3].quantity= 2323;
// more products could be linked to the existing ones
newitem= calloc(1, sizeof product);
newitem->type= 231;
newitem->quantity= 231231;
t[2][3].next= newitem;
// now list them via below function
list_all(t,n,m);
....
void list_all(product **t , int size_n , int size_m)
{
int i,j;
product *p;
for(i=0;i<size_n;i++){
printf("--- Corridor ---: %d\n", i);
for(j=0;j<size_m;j++){
printf("--- Shelf ---: %d\n",j);
p= &t[i][j];
do {
printf("product:%d quantity:%d", p->type, p->quantity);
p= p->next;
} (while p!=NULL);
}
}
}
另请参阅我对艾蒂安的回答的评论以了解更多详细信息。
关于C : Passing bi-dimensional array of pointers as argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873559/