C语言:struct和typedef

2022-08-06,,

1、没有设置结构体名,相当于一个匿名结构体,没有结构体名,后面就没法用该结构体定义新的变量。

#include<stdlib.h>
#include<stdio.h>
struct{
	int x;
	int y;
}Test;
int main()
{
	Test.x = 100;
	printf("%d",Test.x);
} 

2、设置了结构体名a,就可以利用struct a Test2, 来构造一个新的结构体变量Test2,相比上一个的优点是可以直接在main函数里继续构造新的结构体变量(因为有结构体名字了)

#include<stdlib.h>
#include<stdio.h>
struct A{
	int x;
	int y;
}Test1;
int main()
{
	struct A Test2;
	Test1.x = 50;
	Test2.x = 100;
	printf("%d,%d",Test1.x,Test2.x);
} 

 

3、使用 typedef 的结构体,其实末尾这里的Test1,Test2 不是 结构体的变量,而都是struct B的别名,也就是说使用 typedef 的时候没有默认的结构体变量,需要构造新的结构体变量的话,必须通过main函数里的 Test1 test1 或者 Test2 test2来构造一个结构体变量 test1或者test2,相比2来说,拥有typedef 的结构体少了一个能够设置初始的结构体变量的地方,但是在main函数中可以方便的少写 struct 这个关键字

#include<stdlib.h>
#include<stdio.h>
typedef struct B{
	int x;
	int y;
}Test1,Test2;
int main()
{
	Test1 test1;
    Test2 test2;
	test1.x = 50;
    test2.x = 100;
	printf("%d",test1.x);
} 

4、这里相当于结构体没有名字,是一个匿名的结构体,此时末尾的Test也是一个别名而已,只不过是匿名结构体的别名。

​
#include<stdlib.h>
#include<stdio.h>
typedef struct{
	int x;
	int y;
}Test;
int main()
{
	Test test;
	test.x = 100;
	printf("%d",test.x);
} 

​

 总结

有typedef的时候,末尾Test的这个位置就变成了结构体的别名,就是等价struct A。

没有typedef的时候,末尾Test的这个位置就是一个结构体变量。struct后面有名字就方便后续增加结构体变量,没有名字就是一个匿名的结构体,后续不能增加结构体变量。

 

本文地址:https://blog.csdn.net/YiXiao1997/article/details/107301142

《C语言:struct和typedef.doc》

下载本文的Word格式文档,以方便收藏与打印。