2016-03-03 81 views
2

我无法弄清楚如何获得与下面的代码相同的结果,但是使用结构体。如何结合二维数组和动态内存分配使用结构体

我的目标是通过使用结构创建一个动态分配的二维数组初始化为全零,但我不知道我在做什么错。我自己尝试了很多东西,而且我在网上发现了这些东西,而且它们都不起作用。

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,所以这对我来说是新的。请帮忙,谢谢。

+1

'BinaryMatrix * A; A-> NUM_ROWS;'。那就是问题所在。 'A'是一个未初始化的变量,不能被解除引用。你首先需要为'A'设置'malloc'内存。 – kaylum

回答

0
BinaryMatrix* A; 
A->num_rows = num_rows; 

这是你的问题;你正在解引用一个未指向的d指针。您需要先malloc a BinaryMatrix并将其分配给A以便能够取消其字段。

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

刚刚尝试过,但它似乎仍然会导致分段错误。我换了一行:BinaryMatrix * A;进入BinaryMatrix * A = malloc(sizeof(BinaryMatrix));像你说的。 –

+0

我试过你的代码只改变了这一行代码(当然插入一个main()函数),对我来说工作得很好。我可以发布下面的代码,如果它有帮助... – petyhaker

+0

你是对的,它确实有效。我收到的分段错误来自其他地方,而不是这个功能。非常感谢大家。 –