c - 结构体内部的结构体?

标签 c pointers struct linked-list

这是我的讲师发送的示例代码的代码片段。 我不知道其中的逻辑。请耐心等待,我目前正在学习计算机科学专业的学生。编辑:看起来这是一个链接列表。

struct db {
    int value;
    struct db *next;
} *head, *tail, *curr;

void pushF()
{
    int input;
    system("CLS");
    printf("\n\n\tInput value: ");
    scanf("%d", &input);

    curr = (struct db*) malloc(sizeof(struct db));
    curr->value = input;

    if (head == NULL) {
        head = tail = curr;
        head->next = NULL;
    } else {
        curr->next = head;
        head = curr;
    }
}

如果输入为1, 我最好的猜测是:

  • 每个结构体名称(head、tail 和 curr)都有三个不同的“int 值”和 ( struct data *next ) - 我不明白
  • 程序开始时会提示输入值
  • curr = (struct db*) malloc(sizeof(struct db)); 我不明白
  • 设置 curr 的整数值至 1
  • 如果头是 NULL那么..我不明白
  • head = tail = curr - 我不明白。我最好的猜测是这是一条链条。
  • 将头的下一个指针设置为 NULL .
  • 否则将指针设置为 curr到头并将头设置为 curr .

最佳答案

这不是结构中结构的示例。相反,struct db *next 只是将结构成员 next 声明为指向 struct db 的指针。

each of the struct name (head, tail and curr) all have three different "int value" and (struct data *next)

代码创建了 3 个指向 struct 的“实例”指针,head(指向列表第一个节点的指针)、curr(当前节点)、tail(指向列表最后一个节点的指针)。

curr = (struct db*) malloc(sizeof(struct db));

为一个节点分配内存空间。

sets the integer value of curr to 1

它将 curr->value 设置为 1。

if head is NULL ... head = tail = curr

如果列表为空,则将 head 和 tail 设置为列表中唯一的节点。

sets the pointer next on head to NULL.

这不是一个好方法,最好设置 curr->next == NULL,这样更容易理解。

sets the pointer next on curr to head and sets head to curr.

这样做是为了将当前节点插入到列表的开头。假设列表以一个节点 A 开始,那么您有:

head -> A
A -> NULL   (A.next = NULL)
tail -> A

然后假设您插入一个节点 B,在此之后您有:

head -> B
B -> A      (B.next = &A)
A -> NULL   (A.next = NULL)
tail -> A

关于c - 结构体内部的结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768005/

相关文章:

c - ELF64/x86_64和内存映射段的起始地址(对于共享对象)

c - 如何修复段错误

C - 结构构造函数和解构函数

我们可以这样传递结构成员吗?

c - 取消引用指向 pcap_t 结构的不完整类型的指针

c - POSIX 信号量/线程无法正常工作?

c - 用 C 语言编写打印方法

C fread() 一个结构体

ios - 使用各种结构调用 func

C 从字符到函数名