C : Passing bi-dimensional array of pointers as argument

标签 c pointers data-structures linked-list

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

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/

相关文章:

c - 添加到字符串开头的额外字符?

代码未正确显示输出

c - 尝试将指针取消引用回结构中

c - 这两个指针有何不同?

C中按值调用函数

c - 不兼容的指针类型 - 试图从另一个函数修改数组

python - 当我不知道会有多少层时,如何遍历数据结构的所有层级以提取所有数据?

c - 打印文档中的特定行时出现无限循环

c++ - 存储数据结构c++

java - 在 Java 中按值映射自动排序