c - 由 2 个结构组成的链表。接入节点

标签 c pointers struct linked-list

我正在尝试学习基础知识,谁会想到,指针正在杀死我。我想创建一个基本的链表。为此,我创建了两个结构体,一个 linkedList,它有 3 个指针,一个用于第一个节点,一个用于当前节点,一个用于最后一个节点。我希望这能够更轻松地插入新节点。 然后我有节点,它们只是一个值和一个指向新节点的指针。

typedef struct linkedList linkedList;
struct linkedList{
    struct node* start;
    struct node* last;
    struct node* current;
};

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

我创建了一个新节点

node* newNode(int value){
    node* newNode = (node*)malloc(sizeof(node));
    newNode->next = NULL;
    newNode->value = value;
    return newNode
}

现在,主要是我创建一个新的链接列表

linkedList List;
List.start = NULL;
List.current = NULL;
List.last = NULL;

node* node1 = newNode(1);

List.start = node1;
List.current = node1;
List.last = node1;

现在,我如何使用链表访问节点的内容? 编译器说,如果我这样做,我会像在 Java 中那样做 “错误:请求非结构或 union 中的成员‘值’” 如果我尝试

List.start.value = 1;

如果我尝试

(*(List.start)).value = 1;

它可以编译,但给我一个段错误。 我真的不确定指针的工作方式。我通过谷歌找到的链表都只使用节点,没有可交互的主链表。我在学校类(class)中几乎陷入了困境,因此我对 C 的复杂性的了解是有限的。

最佳答案

    List.start.value = 1;

上面的方法不起作用。 List.start会给出node1,所以接下来你需要做node1->value,因为node1是结构类型的指针。

因此使用以下语句:

    (List.start)->value = 200;

或者你也可以像这样使用它:

    (*(List.start)).value = 200;

用这个测试这些:

    printf("accessing : %d\n", node1->value);

关于c - 由 2 个结构组成的链表。接入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47237996/

相关文章:

c - C 程序中的错误与 xx 的类型冲突以及 xx 的先前隐式声明在这里

c - 在C函数中返回struct

c - 我想搜索并显示一个 “contact”的信息,但是没有用

c - 如何在不知道大小的情况下分配结构数组

c++ - 在 Visual Studio 2005 中的取消引用指针的地址上设置数据断点

c - 信号处理程序中的 pthread_exit()

c - 禁食期警告 :"Arithmetic Overflow: 32-bit value is shifted, then cast to 64-bit value."

C - 空指针如何成为常量?

c - 出现段错误 - 尝试从我的结构中检索数据

c - 在 C 中创建函数指针结构时从未完成的类型错误