gpt4 book ai didi

C : Passing bi-dimensional array of pointers as argument

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:25 25 4
gpt4 key购买 nike

我正在使用一个二维指针数组,每个指针都指向一个产品链表。我想构建一个函数来列出所有列表中的所有产品。这是我的结构:

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

有关更多详细信息,另请参阅我在 Etienne 的回答中的评论。

关于C : Passing bi-dimensional array of pointers as argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873559/

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