【发布时间】:2020-01-18 16:03:13
【问题描述】:
struct matrix {
int m, n; // m rows, n columns
int** data;
char name[64];
};
struct matrix* alloc_matrix(const char* name, int m, int n) {
struct matrix *mat = malloc(sizeof(struct matrix));
strcpy(mat->name, name);
mat->m = m;
mat->n = n;
mat->data = (int**)malloc(sizeof(m) * (m * n));
return mat;
}
int main() {
struct matrix* mat1 = alloc_matrix("mat1", 4, 4);
mat1->data[0][0] = 2; <------------------------------ This line causes the error
return EXIT_SUCCESS;
}
所以我想实现矩阵。我定义了一个结构矩阵,其中包含一个矩阵的名称、行数、列数和数据。使用函数 alloc_matrix 我想为结构对象分配内存。但是这个函数出了点问题,因为如果我想在分配的对象上检索或设置数据,我会得到一个运行时内存错误。
希望有人对动态数据分配有更多经验并看到问题。
【问题讨论】: