【问题标题】:Why do I get "incompatible pointer type" when assigning pointers to a multidimensional array为什么将指针分配给多维数组时会出现“不兼容的指针类型”
【发布时间】:2019-03-27 22:34:58
【问题描述】:

我正在尝试使用一个节点矩阵来保存一个 int 值,该值会根据其邻居在每次迭代中发生变化,所以我决定我应该有一个“节点”结构来保存它的值和节点列表很近,但是在编译时将节点分配给列表时会收到以下警告:

警告:来自不兼容指针类型的赋值 [-Wincompatible-pointer-types] n -> neighbours[0] = table[M - 1][N - 1];

当我尝试访问结构内的任何变量时,该警告会导致我的节点无法初始化,从而导致分段错误(我认为是因为它为 NULL)。

这是我的代码,希望你能帮助我

...
typedef struct node {
    int state;
    struct Node** neighbours;
} Node;

Node* node_init(int i, int j, int M, int N, Node*** table) {
    Node* n = malloc(sizeof(Node));
    n -> state = -1;
    n -> neighbours = malloc(sizeof(Node*)*8);
    if (i == 0 && j == 0) {  // (0, 0)
        n -> neighbours[0] = table[M - 1][N - 1];  // Here is the problem
        n -> neighbours[1] = table[M - 1][j];
        n -> neighbours[2] = table[M - 1][j + 1];
        n -> neighbours[3] = table[i][N - 1];
        n -> neighbours[4] = table[i][j + 1];
        n -> neighbours[5] = table[i + 1][N - 1];
        n -> neighbours[6] = table[i + 1][j];
        n -> neighbours[7] = table[i + 1][j + 1];
    } ...  // for all cases
    return n;

Node*** table = malloc(sizeof(Node**)*M);          // M is the amount of rows
for (int i=0; i < M; i++) {
    Node** nodes = malloc(sizeof(Node*)*N);        // N is the amount of cols
    table[i] = nodes;
    for (int j=0; j < N; j++) {
        Node* node = node_init(i, j, M, N, table); // wont reach here
        table[i][j] = node;
        fscanf(fp, "%i", &(node -> state));        // ain't relevant

    }
}
...

我知道我第一次这样做

n -> neighbours[0] = table[M - 1][N - 1]

我正在分配一个由 table 的位置指向的随机值,但我认为这不是问题,对吧?

无论如何,希望你能帮助我

谢谢你:)

【问题讨论】:

  • 这个问题,正如它最初提出的那样,已经得到回答。请不要将其编辑成完全不同的东西。相反,发布一个新问题,不要理会这个问题。
  • ^ 或在发布新问题之前尝试调试程序

标签: c pointers struct


【解决方案1】:

table[M - 1][N - 1] 是一个Node*,在应用typedef struct node { /* ... */ } Node; 之后是一个struct node*n -&gt; neighbours[0]struct Node*。由于 C 区分大小写,因此它们实际上是指向两个完全不同的结构的指针。

【讨论】:

  • 是的!刚注意到,谢谢,不敢相信哈哈哈。但是,我仍然遇到分段错误:(
猜你喜欢
  • 1970-01-01
  • 2014-10-10
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多