結構體嵌套:
將一個已經聲明的結構體在另一個結構體內作爲成員變量進行定義,並在外層結構體初始化的同時最自己進行行初始化,使用花括號包裹自身成員變量。
打印時注意爲:結構體名稱.結構體成員結構體.結構體成員結構體的成員
#include <stdio.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char title[128];
char author[40];
float price;
struct Date date; //結構體的嵌套
char publisher[40];
} book = {
"《C語言》",
"abc",
99.9,
{2020,02,29},
"出版社"
};
int main(void)
{
printf("書名:%s\n", book.title);
printf("作者:%s\n", book.author);
printf("售價:%f\n", book.price);
//注意這裏的輸出方式:三個數據%d%d%d中間的-也會打印,每個數據尋找到最底層,book.date.year
printf("出版日期:%d-%d-%d\n", book.date.year, book.date.month, book.date.day);
printf("出版社:%s\n", book.publisher);
return 0;
}
結構體數組:
同定義結構體的形式。
僅僅把定義時的數組名換爲數組名+長度。
struct 結構體名稱 { 結構體成員; } 數組名 [長度];
第二種:
struct 結構體名稱 { 結構體成員; };
struct 結構體名稱 數組名[長度];
初始化結構體數組:
可以在定義的同時進行初始化:
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char title[128];
char author[40];
float price;
struct Date date; //結構體的嵌套
char publisher[40];
};
struct Book book[3] = { //定義長度爲三的結構體數組book,book內嵌結構體date。初始化時用{}。
{"《C語言》","abc",99.9,{2020,02,29},"出版社"},
{"《C++》","abcd",99.9,{2020,02,29},"出版社"},
{"《C#》","abcde",99.9,{2020,02,29},"出版社"},
};
畢竟本質還是數組,若想全部打印,只需要加入一點循環就可以了~
for (int i = 0; i < 3; i++)
{
printf("書名:%s\n", book[i].title);
printf("作者:%s\n", book[i].author);
printf("出版日期:%d-%d-%d\n", book[i].date.year,book[i].date.month,book[i].date.day);
}
結構體指針:
指針可以指向任何數據,當然也可以指向結構體,指向結構體變量的指針我們稱爲結構體指針。
struct Book * pt就是一個指向Book結構體類型的指針變量pt,也具備指針的特點,指向的數據類型放在前面。
數組名指向數組第一個元素的地址,所以可以把數組名的地址賦值給指針。但是,結構體不是這樣的,結構體的變量名不是指向結構體的地址的,所以對結構體變量的取值必須使用取址符&。
pt = &book;
通過結構體指針訪問結構體成員有兩種方法:
1,(* 結構體指針).成員名-----------與普通指針同理,對結構體變量解引用就是結構體變量就可以進行(.)運算。
2,結構體指針->成員名------------(->)也是運算符,爲成員選擇(指針)運算符,(.)是成員選擇(對象)運算符,他們兩個使用形式相同。區別就是一個是對象取成員,一個是指向對象的指針取成員,實現上是完全等價的。
使用第一種解引用方法訪問結構體成員:
#include <stdio.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char title[128];
char author[40];
float price;
struct Date date; //結構體的嵌套
char publisher[40];
} book = {
"《C語言》",
"abc",
99.9,
{2020,02,29},
"出版社"
};
int main(void)
{
struct Book *pt; //指向數據類型爲Book結構體的指針*pt
pt = &book; //指針pt指向了已經初始化的結構體變量book
//均爲解引用的形式打印出數據
printf("書名:%s\n", (*pt).title);
printf("作者:%s\n", (*pt).author);
printf("售價:%f\n", (*pt).price);
printf("出版日期:%d-%d-%d\n", (*pt).date.year, (*pt).date.month, (*pt).date.day);
printf("出版社:%s\n", (*pt).publisher);
return 0;
}
使用(->)打印:
int main(void)
{
struct Book *pt; //指向數據類型爲Book結構體的指針*pt
pt = &book; //指針pt指向了已經初始化的結構體變量book
printf("書名:%s\n",pt->title);
printf("作者:%s\n", pt->author);
printf("售價:%f\n", pt->price);
//注意這裏的輸出方式:三個數據%d%d%d中間的-也會打印,每個數據尋找到最底層,book.date.year
printf("出版日期:%d-%d-%d\n", pt->date.year, pt->date.month, pt->date.day);
printf("出版社:%s\n", pt->publisher);
return 0;
}