我无法弄清楚如何获得与下面的代码相同的结果,但是使用结构体。如何结合二维数组和动态内存分配使用结构体
我的目标是通过使用结构创建一个动态分配的二维数组初始化为全零,但我不知道我在做什么错。我自己尝试了很多东西,而且我在网上发现了这些东西,而且它们都不起作用。
printf("Enter the number of rows: ");
scanf("%d", &r);
printf("Enter the number of columns: ");
scanf("%d", &c);
int** list = (int**)malloc(r * sizeof(int*));
for (i = 0 ; i < r ; i++) {
list[i] = (int*) malloc(c * sizeof(int));
for (x = 0 ; x < c ; x++) {
list[i][x] = 0;
}
}
我对结构代码如下:
typedef struct {
int num_rows;
int num_cols;
int** data;
} BinaryMatrix;
BinaryMatrix* ConstructBinaryMatrix(int num_rows,int num_cols);
BinaryMatrix* ConstructBinaryMatrix(int num_rows, int num_cols) {
if (num_rows <= 0 || num_cols <= 0) {
printf("Error.\n");
return EXIT_FAILURE;
} else {
int i,x;
BinaryMatrix* A;
A->num_rows = num_rows;
A->num_cols = num_cols;
A->data = (int**) malloc(A->num_rows * sizeof(int*));
for (i = 0; i < num_rows; i++) {
(A->data)[i] = malloc(A->num_cols * sizeof(int*));
for (x = 0; x < A->num_cols; x++) {
(A->data)[i][x] = 0;
}
}
return A;
}
}
BinaryMatrix* M;
printf("Enter the number of rows: ");
scanf("%d", &num_rows);
printf("Enter the number of cols: ");
scanf("%d", &num_cols);
M = ConstructBinaryMatrix(num_rows, num_cols);
我收到的错误是分段错误。这似乎是在第一次malloc调用完成的时刻发生的。
我在学C,需要一些指导。我来自Python,所以这对我来说是新的。请帮忙,谢谢。
'BinaryMatrix * A; A-> NUM_ROWS;'。那就是问题所在。 'A'是一个未初始化的变量,不能被解除引用。你首先需要为'A'设置'malloc'内存。 – kaylum