简体   繁体   English

动态 memory 分配矩阵写为结构

[英]Dynamic memory allocation for a matrix written as a struct

I need to allocate memory for a struct that contains a matrix:我需要为包含矩阵的结构分配 memory:

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

And i need to do all of it inside one separate function.我需要在一个单独的 function 中完成所有这些工作。 I'm a bit confused because I'm not sure on how am I supposed to allocate memory for a matrix [row*column] that is inside of a struct that also contains numerical information about the row and column size.我有点困惑,因为我不确定我应该如何为结构内部的矩阵 [row*column] 分配 memory,该结构还包含有关行和列大小的数字信息。 By my (obviously flawed) logic, that'd mean I'd need to allocate memory for the struct, input the info on row and column size, and then additionaly allocate memory for the matrix that's indside of a struct.按照我的(明显有缺陷的)逻辑,这意味着我需要为结构分配 memory,输入行和列大小的信息,然后为结构内部的矩阵额外分配 memory。 I'm a bit confused by it, but this is what I've come up with so far:我对此有点困惑,但这是我迄今为止想出的:

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

And then inside of main() I do:然后在main()里面我做:

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

And this code works properly, but my task is to completely allocate the memory for all data inside of one function of MATRIX* type (that returns fully allocated struct + matrix) without ever jumping back to main() to do the scanning.这段代码工作正常,但我的任务是为一个MATRIX*类型的 function 内的所有数据完全分配 memory (返回完全分配的结构 + 矩阵),而无需跳回main()进行扫描。

You can change your alloc function to allocate a MATRIX internally and return it as the function result, like so:您可以更改您的alloc function 以在内部分配MATRIX并将其作为 function 结果返回,如下所示:

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

Your main then becomes:然后你的main变成:

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

The casts before malloc are not necessary (in C), but they are harmless. malloc之前的强制转换不是必需的(在 C 中),但它们是无害的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM