c语言结构体嵌套
转载自:https://blog.csdn.net/zhudong10/article/details/49496221
C语言中结构体是一种构造类型,和数组、基本数据类型一样,可以定义指向该种类型的指针。结构体指针的定义类似其他基本数据类型的定义,格式如下
struct 结构体名 * 指针名;
比如:
struct person{char[20] name; int age;};//先定义一个人的结构体
struct person *p;//然后可以定义一个人的结构体指针
struct person p1 = {"zhangsan",20};
*p = &p1;//结构体指针的初始化
当定义结构体时,如果结构体中的成员又是一个结构体,那么就称为结构体的嵌套。比如:
struct room{
int chair;
int computer;
struct person children;
};
嵌套的结构体初始化方式如下:
struct room r1 = {1,1,{"xiaohong",7}};
嵌套结构体的初始化参照基本结构体的初始化方式,对结构体的元素分别进行初始化。
结构体中不可以嵌套自身的结构体,但是可以嵌套指向自身的指针。
关于上面所述的结构体嵌套及嵌套指向自身的结构体指针,下面有几个实例:
-
结构体的嵌套以及结构体指针 -
#include "stdafx.h" -
#include -
int main(int argc, char* argv[]) -
{ -
//结构体指针 -
struct office{ -
int chair; -
int computer; -
} ; -
struct office officeOne = {10,10}; -
struct office *p = &officeOne; -
printf("chair = %d,computer = %d\n",(*p).chair,(*p).computer); -
return 0; -
}
-
#include "stdafx.h" -
#include -
//结构体指针以及结构体嵌套 -
struct employee{ -
char name[10]; -
int age; -
}; -
int main(int argc, char* argv[]) -
{ -
//结构体嵌套 -
struct office{ -
int chair; -
int computer; -
struct employee em; -
} ; -
struct office officeOne = {10,10,{"zhangsan",25}}; -
struct office *p = &officeOne; -
printf("chair = %d,computer = %d\nname = %s,age = %d\n",(*p).chair,(*p).computer,officeOne.em.name,officeOne.em.age); -
return 0; -
}
-
#include "stdafx.h" -
#include -
//结构体指针以及结构体嵌套结构体指针 -
int main(int argc, char* argv[]) -
{ -
//结构体指针 -
struct office{ -
int chair; -
int computer; -
struct office *of1; -
} ; -
struct office officeOne = {10,10,NULL}; -
struct office officeTwo = {10,10,&officeOne}; -
printf("chair = %d,computer = %d\nchair1 = %d,computer1 = %d\n",officeTwo.chair,officeTwo.computer,(*(officeTwo.of1)).chair,(*(officeTwo.of1)).computer); -
return 0; -
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
