【问题标题】:Dynamic memory allocation for a matrix written as a struct以结构形式编写的矩阵的动态内存分配
【发布时间】:2021-08-27 21:51:09
【问题描述】:

我需要为包含矩阵的结构分配内存:

typedef struct matrix{
int row;
int column;
int **data;
}MATRIX;

我需要在一个单独的函数中完成所有这些工作。我有点困惑,因为我不确定我应该如何为结构内部的矩阵 [row*column] 分配内存,该结构还包含有关行和列大小的数字信息。根据我的(明显有缺陷的)逻辑,这意味着我需要为 struct 分配内存,输入有关行和列大小的信息,然后为结构内部的矩阵额外分配内存。我对此有点困惑,但这是我迄今为止想出的:

int** alloc(MATRIX *array , int row , int column){

int i;

array->data = (int**)malloc(row * sizeof(int*));

for(i=0; i<br_red; i++){
    array->data[i] = (int*)malloc(column * sizeof(int));
}
return array->data;
}

然后在main() 里面我做:

MATRIX *array = (MATRIX*)malloc(sizeof(MATRIX));
scanf("%d" , &array->row);
scanf("%d" , &array->column);
array->data = alloc(array , array->row , array->column);

这段代码工作正常,但我的任务是为MATRIX* 类型的一个函数(返回完全分配的结构+矩阵)内的所有数据完全分配内存,而无需跳回main() 执行扫描。

【问题讨论】:

  • 您不需要“扫描”来分配内存。看起来您需要做的就是更改 alloc 的类型,使其返回 MATRIX *,将 malloc(sizeof(MATRIX)) 移动到函数中,然后返回值。
  • 手动计算适当索引的一维数组会更有效——代价是寻址不太方便;您可以提供帮助函数以便于访问,例如。 G。 int at(Matrix* m, size_t row, size_t column) { return m-&gt;data[row*m-&gt;column + column]; },类似 setAt 函数。

标签: c pointers matrix struct dynamic-memory-allocation


【解决方案1】:

您可以更改 alloc 函数以在内部分配 MATRIX 并将其作为函数结果返回,如下所示:

MATRIX* alloc (int row , int column)
{
    MATRIX *array = (MATRIX *) malloc (sizeof (MATRIX));
    array->data = (int**)malloc(row * sizeof(int*));
    for (int i = 0; i < row; i++)
        array->data[i] = (int*)malloc(column * sizeof(int));
    return array;
}

您的main 则变为:

int row, column;
scanf("%d" , &row);
scanf("%d" , &column);
MATRIX *array = alloc (row, column);

malloc 之前的强制转换不是必需的(在 C 中),但它们是无害的。

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    相关资源
    最近更新 更多