我对 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/