【问题标题】:Assignment from incompatible pointer type when using Linked Lists使用链表时从不兼容的指针类型赋值
【发布时间】:2015-03-17 23:25:56
【问题描述】:

我正在尝试使用一个简单的链表示例,以尝试了解使用它们背后的基本思想,以供以后使用。但是,我对如何将列表中的每个节点设置为某个值感到困惑。即在这里,我想将成员“a”设置为“b”的地址,将成员“b”设置为c的地址。但是,这是发生警告的地方,

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

struct List
{
    int data;
    struct List * next;
};

int main (int argc, char * argv[])
{

    struct List * a = malloc(sizeof(struct List));
    a->data = 0;
    a->next = NULL;

    struct List * b = malloc(sizeof(struct List));
    b->data = 1;
    b->next = NULL;

    struct List * c = malloc(sizeof(struct List));
    c->data = 2;
    c->next = NULL;

    a->next = &b; //warning occurs here
    b->next = &c;
}

有没有办法在没有任何警告的情况下设置 a->next (a.next) 和 b->next(b.next) 的值?

【问题讨论】:

  • 您希望a-&gt;next 指向b 指向的 malloc 分配的空间。不要指针b.
  • 那么第一个和最后一个(malloc 调用)就可以了吗?只有 * b 一个?
  • 所有 malloc 调用都很好,问题是给你警告的两行

标签: c pointers struct linked-list


【解决方案1】:

a-&gt;next 的类型为 struct List *

b 的类型为 struct List *

&amp;b 的类型为 struct List **

您可能打算这样做:a-&gt;next = b;

【讨论】:

    【解决方案2】:

    b 已经是指向 struct List 的指针,因此您不需要 &amp; 运算符。

    只要做:

    a->next = b;
    

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2019-08-09
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      相关资源
      最近更新 更多