[英]How to use structs with 2D Arrays and Dynamic Memory Allocation
我很難弄清楚如何獲得與以下代碼相同的結果,但是有一個結構。
我的目標是使用該結構創建一個初始化為全零的動態分配2D數組,但我不確定自己做錯了什么。 我自己嘗試了很多東西,並且在網上找到了,但似乎都沒有用。
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 = num_rows;
這是你的問題; 您正在取消引用未malloc
的d指針。 首先,您需要malloc
一個BinaryMatrix
並將其分配給A
能夠取消引用其字段。
BinaryMatrix* A = malloc(sizeof(BinaryMatrix));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.