结构体数组和结构体指针
目录:
一、结构体嵌套
二、结构体数组
三、初始化结构体数组
四、结构体指针
一、 结构体嵌套
struct Date
{
int year;
int month;
int day;
};
例子
#include <stdio . h>
struct Date
{
int year;
int month;hio
int day;
};
struct Book
{
char title[128];
char author[40];
float price ;
struct Date date;
char publisher[40];
}book = {
“《带你学C带你飞》”,
"小甲鱼 ",
48.8,
{2017, 11, 11},
“清华大学出版社“
};
int main(void)
{
printf(“书名:%s\n”,book.title);
printf(“作者:%s\n”,book.anther);
printf(“售价:%.2f\n”,book.price);
printf(“出版日期:
%d-%d-%d\n”,book.date.year,book.date.month,book.date.day);
printf(“出版社:%s\n”,book.publisher);
return 0;
}
书名:《带你学C带你飞》
作者:小甲鱼
售价:48.80
出版日期:2017-11-11
出版社:清华大学出版社
二、 结构体数组
结构体数组跟之前数组概念大致是相似的, 每个数组的元素不再是简单的基础类型,而是结构体类型数据,所以每个结构体数组元素都包含该结构体所有成员。
- 第一种方法是在声明结构体的时候进行定义:
strut 结构体名称
{
结构体成员;
}数组名 [长度];
- 第二种方法是先声明一个结构体类型(比如上面Book),再用此类型定义一个结构体数组:
struct 结构体名称
{
结构体成员;
};
struct 结构体名称 数组名[长度];
三、 初始化结构体数组
结构体数组定义的同时,同样可以进行初始化,例如:
struct Book book[3] = {
{"《零基础入门学习Python》”,“小甲鱼",49.5,
{2016,11,11},“清华大学出版社"},
{"《零基础入门学习Scratch》","不二如是",49.9,
{2017, 10,1}, "清华大学出版社"},
{"《带你学C带你飞》","小甲鱼",49.9,{2017, 11,
11},“清华大学出版社"}
};
四、结构体指针
通过结构体指针访问结构体成员有两种方式:(*结构体指针).成员名
结构体指针->成员名
检引用和指针的方式下运行结构正常均正常
检引用的形式:
int main(void)
{
struct Book *pt;
pt = &book;
printf("书名:%s\n",(*pt).title);
printf("作者:%s\n",(*pt).author);
printf("售价:%.2f\n",(*pt ).price) ;
printf("出版日期∶%d-%d-%d \n",(*pt).date.year,(*pt).date.month,(*pt).date.day ) ;
printf(""出版社: %s \n",(*pt ).publisher) ;
return 0;
运行结果:
书名:《带你学c带你飞》
作者:小甲鱼
售价:48.80
出版日期:2017-11-11
出版社︰清华大学出版社
[fishc@bogon sle43]$
指针的形式:
int main(void)
{
struct Book *pt;
pt = &book;
printf("书名:%s\n",(*pt).title);
printf("作者:%s\n",(*pt).author);
printf("售价:%.2f\n",(*pt ).price) ;
printf("出版日期∶%d-%d-%d \n",(*pt).date.year,(*pt).date.month,(*pt).date.day ) ;
printf(""出版社: %s \n",(*pt ).publisher) ;
return 0;
7 substitutions on 5 lines
运行结果:
书名:《带你学c带你飞》
作者:小甲鱼
售价:48.80
出版日期:2017-11-11
出版社︰清华大学出版社
[fishc@bogon sle43]$