结构体的声明与定义

struct为结构体关键字,tag为结构体的标志,member-list为结构体成员列表,其必须列出其所有成员;variable-list为此结构体声明的变量。

struct tag

 {
 	member-list;
 } variable-list ;

示例代码:

struct Student
{
	char 	name[10];
	int   		age;
	int    	score[5];
}stu1;

结构体的2种定义方式:

1. 常规定义:

struct Student
{
	char 	name[20];
	int 		age;
	int		score[5];
};
struct Student s1 = {"zhangsan",22,{1,2,3,4,10}};

2.尾部定义

struct
{
	char		name[10];
	int		age;
	int		score[5];
}stu1 = {"张三",20,{150,110,20,34,114}},stu2;

结构体之间可以相互赋值

stu1 = stu2;此时stu2 ={"张三",20,{150,110,20,34,114}};

无名结构体,只能通过尾部定义创建对象

struct 
{
	char 	name[20];
	int 		age;
	int		score[5];
}s1,s2,s3;

通过结构体指针动态创建对象

struct Student
{
	char 	name[20];
	int 		age;
	int		score[5];
}*s;

s = (struct Student*)malloc(sizeof(struct Student));

结构体的成员可以包含其他结构体(结构体的嵌套),也可以包含指向自己结构体类型的指针,而通常这种指针的应用是为了实现一些更高级的数据结构如链表和树等。

结构体的嵌套:

 struct SIMPLE
{
	char		name[10];
}

struct COMPLEX{
	char		name[100];
	struct	SIMPLE i;
};
包含指针的结构体:
struct NODE{
    char			name[10];
    struct	NODE	*next_node;
};

结构体对象如何访问内部元素;

静态对象:通过点运算符"."

struct 
{
	char 	name[20];
	int 	age;
	int	score[5];
}s1 = {"张三,20,{150,110,20,34,114}"},*p;
void main()
{
      p = &stu;
      printf("%s",stu.name);
      printf("%s",p->name);
}可以看到两个输出结果都是一样的;

动态对象:通过指向符"->"
如果对象内部存在指针元素,那么在使用以前要分配内存空间;






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值