【问题标题】:Error when using multidimensional-array of 0 length使用长度为 0 的多维数组时出错
【发布时间】: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


【解决方案1】:

在 C 中,类型是静态的,因此这意味着当您使用它时(编译完成时)必须完全知道每种类型。对于二维数组,这意味着必须知道所有维度才能使语言能够访问各个单元格。使用一个公式来访问数组,该公式需要它已使用的索引部分的大小。一个单元格是单元格大小,但对于一个单元格数组,您必须知道在该方向上有多少个单元格。

但是,有一种解决方法允许您使用带有[] 括号的索引,并且不需要知道任何大小,只需要知道单个单元格的大小。您必须使用指针,如下例所示:

double **new_matrix(int rows, int cols)
{
    double **res = malloc(rows * sizeof(double *));
    int i;
    for (i = 0; i < rows; i++)
        res[i] = malloc(cols * sizeof(double));
    return res;
}
void free_matrix(double **matrix, int rows)
{
    int i;
    for (i = 0; i < rows; i++) free(matrix[i]);
    free(matrix);
}
...
double **matrix = new_matrix(24, 3);
matrix[12][1] /* will access correctly row 13 and column 2 element */
...
free(matrix, 24); /* will free all allocated memory */

有一些解决方案允许您分配整个矩阵(以及一堆中的指针(并允许在矩阵事物上直接使用free(3)),但我将此作为练习留给读者:)

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 2017-11-10
    • 2017-08-27
    • 2013-10-10
    • 2013-08-21
    相关资源
    最近更新 更多