gpt4 book ai didi

c - 如何将结构与二维数组和动态内存分配一起使用

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:55 25 4
gpt4 key购买 nike

我无法弄清楚如何使用结构获得与以下代码相同的结果。

我的目标是创建一个动态分配的二维数组,通过使用该结构初始化为全零,但我不确定我做错了什么。我自己尝试了很多东西,我在网上找到了很多东西,但似乎都不起作用。

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 的指针。您需要首先 malloc 一个 BinaryMatrix 并将其分配给 A 以便能够取消引用其字段。

BinaryMatrix* A = malloc(sizeof(BinaryMatrix));

关于c - 如何将结构与二维数组和动态内存分配一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com