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 <string.h>
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 <string.h>
//結構體指針以及結構體嵌套
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 <string.h>
//結構體指針以及結構體嵌套結構體指針
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;
}