C中结构中的矩阵

时间:2016-03-24 12:41:00

标签: c matrix struct

我正在尝试将矩阵存储在LinkedList中。但是我收到了一个错误,代码可以编译但无法运行。可能关于内存分配,但我无法弄清楚。

我的结构是这样的:

typedef struct node {
     int** matrix;
     struct node *next;
} node;

struct node *head;
struct node *tail;

我尝试像这样初始化结构:

struct node *init(void) {
     head = (struct node *) malloc(sizeof *head);
     tail = (struct node *) malloc(sizeof *head);

     head->next = tail;
     tail->next = tail;
     return head;
}

我有一个充满1s的矩阵:

int **mat = (int **) malloc(N * sizeof(int *));

for (i = 0; i < N; i++) {
    mat[i] = (int *) malloc(N * sizeof(int));
    for (j = 0; j < N; j++) {
        mat[i][j] = 1;
    }
}

但是当我试图将它附加到列表中时,程序已经崩溃了。

我试图像这样追加:

struct node *l1;
l1 = init();

l1 = append(mat, "t1", N);
int** a3 = returnNode(0, l1);

最后,我的append和returnNode函数是这样的:

struct node *append(int** mat, char* name, int N) {
     struct node *ptr;

     struct node *t;
     ptr = head;
     while (ptr->next != tail)
          ptr = ptr->next;
     t = (struct node *) malloc(sizeof *t);

     t->matrix = (int**) malloc(N * sizeof(int*));
     int i,j;
     for (i = 0; i < N; i++) {
         for (j = 0; j < N; j++) {
             t->matrix[i][j] = (int)malloc(N * sizeof(int*));
         }
     }
     t->matrix = mat;
     t->next = tail;

     ptr->next = t;
     return ptr;
}

int** returnNode(int index, struct node *ptr) {
     int i;
     struct node *t;
     t = (struct node *) malloc(sizeof *t);
     t = head;
     for (i = 0; i < index; i++) {
         t = t->next;
     }

     return t->matrix;
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

错误是:

  

从指针转换为不同大小的整数

t->matrix[i][j] = (int)malloc(N * sizeof(int*));

解决方案: -

在这里,您尝试将地址转换为整数值并将其分配给整数变量位置。

实际问题在于:

(int)malloc(N * sizeof(int*));

malloc返回一个指针,你应该相应地转换它的类型并分别赋值。