【发布时间】:2015-11-30 16:54:20
【问题描述】:
我想在一些结构体中使用二维数组:
typedef struct{
int rows;
int cols;
another_struct *array[][];
}some_struct;
但是好像不能做不完整类型的多维数组,所以我选择another_struct *array[0][0];
并以这种方式分配:
some_struct *allocate_some_struct(int rows, int cols){
some_struct *p;
uint32_t length;
length = sizeof(some_struct) + rows * sizeof(another_struct *[cols]);
p = malloc(length);
p->rows = rows;
p->cols = cols;
return (p);
}
但每当我尝试以这种方式访问它时:((another_struct *[p->rows][p->cols])p->array)[i],我就会得到这个error: used type 'another_struct *[p->rows][p->cols]' where arithmetic or pointer type is required。
虽然(*((another_struct *(*)[p->rows][p-cols])&(p->array)))[i],工作得很好。
所以我的问题是为什么我不能使用第一种语法?和第二个有根本区别吗?
【问题讨论】:
-
编译器如何知道数组元素的排列,因为它不知道行数或列数,无论是不起作用的代码还是“完美运行的代码”好”?
-
好吧,也许我应该加上
p->rows = rows;和p->cols = cols;,这似乎让编译器在转换时知道行数和列数。编辑完成 -
也许您不需要在结构
another_struct *array[][]中明确指定二维数组。如果您不介意,您可以简单地声明一个指针并将数据存储在免费存储中;指针指向一个内存,该内存以您需要的形式保存您需要的数据(二维数组可以看作是数组的数组)。 -
您需要声明它并将其分配为一维数组,并计算出与您的二维索引对应的一维索引。例如。
p->array[r * p->cols + c]. -
如果你想动态二维数组使用
another_struct **array;
标签: c arrays multidimensional-array