c - c中结构体运算符的区别

标签 c

我对 c 中的结构不熟悉,我一直在研究 .运算符和 -> 运算符。但我似乎无法找到解释我想知道的内容的资源。那么,为什么如果我在没有 typedef 的情况下创建结构体,我可以直接使用它,例如“header.first = x”,而不必说“struct header varName”?另外, 和 之间有什么区别。和 -> 在这个例子中,因为在这种情况下我似乎可以互换使用它们。

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

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

struct header{
        int count;
        node *first;
}header;
int main()
{

   node *curptr = (node*)malloc(sizeof(node));
   printf("%p\n",curptr);
   header.first = curptr;
   printf("%p\n",header.first);
   header.count = 10;
   printf("%i\n\n\n",header.count);


   node* current = (node*)malloc(sizeof(node));
   current->data = 5;
   current->next = NULL;
   printf("%i\n",current->data);
   printf("%p",current);
}

最佳答案

struct header { ... } header; 同时创建结构类型 (struct header) 并创建一个全局变量(名为 header,类型为struct header)。它相当于做:

struct header { ... };
struct header header;

当您编写 header.first = x 时,您所做的只是修改名为 header 的全局对象。

typedef struct node { ... } node; 同时创建结构类型 (struct node) 及其 typedef (node)。它相当于做:

struct node { ... };
typedef struct node node;

对于.->:a->b相当于(*a).b。只是syntactic sugar .

关于c - c中结构体运算符的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743478/

相关文章:

c - 如何在不使用任何变量和运算符的情况下编写始终为真的 if 语句?

在结构体中调用malloc

c - 通过调用 getchar 改变程序的行为

C 程序中的 Char 变量行为

c - 为什么函数不会改变变量?

c - C中的冒泡排序数组

c++ - APNS。 C++ : extract Identifier from error responce

c - 在 Linux 中重新传播捕获的信号

c - 如何截获正在写入内存段的指令的地址?

c - Minifilter 哪个标签应该与文件系统字符串缓冲区一起使用?