定义初始化和使用一个结构体
#include <stdio.h>struct Data{int year;int month;int day;};struct Book{char title[128];char author[40];float price;struct Data date;char publisher[40];//结构体值初始化} book = {"凯凯BOOK","凯凯",99.9,{2021,11,11},"武汉"};int main(){printf("书名: %s \n", book.title);printf("日期: %d-%d-%d \n", book.date.year, book.date.month, book.date.day);return 0;}
初始化方法 2
#include <stdio.h>struct Data{int year;int month;int day;};struct Book{char title[128];char author[40];double price;struct Data date;char publisher[40];};int main(){// 初始化结构体内容struct Book book = {"APPLE","凯凯",99.9,{2021,11,11},"武汉"};printf("书名: %s \n", book.title);printf("日期: %d-%d-%d \n", book.date.year, book.date.month, book.date.day);return 0;}
结构体数组
在初始化结构体的名称后面添加 [number] 即可定义一个结构体数组
#include <stdio.h>struct Data {int year;int month;int day;};struct Book {char title[128];char author[40];double price;struct Data date;char publisher[40];};int main() {// 初始化结构体内容struct Book book[2] = {{"APPLE","凯凯",99.9,{2021,11,11},"武汉"},{"KkBOOK","KkBOOK",99.9,{2022,12,12},"KkBOOK"}};printf("书名: %s \n", book[1].title);printf("日期: %d-%d-%d \n", book[1].date.year, book[1].date.month, book[1].date.day);return 0;}
结构体指针
注意: 定义一个结构体指针和普通方式不一样 每个结构体都可以理解为一种类型 需要指定定义某个结构体类型的指针, 指向初始化后的对应结构体地址
#include <stdio.h>struct Data {int year;int month;int day;};struct Book {char title[128];char author[40];double price;struct Data date;char publisher[40];} book = {"凯凯BOOK","凯凯",99.9,{2021,11,11},"武汉"};;int main() {// 结构体指针// 定义一个 Book 类型的结构体指针, 指向初始化后的地址struct Book *pt = &book;// 访问结构体指针// 解引用的方式printf("title: %s \n", (*pt).title);// 箭头方式printf("author: %s \n", pt->author);return 0;}
访问结构体指针
// 解引用的方式printf("title: %s \n", (*pt).title);// 箭头方式printf("author: %s \n", pt->author);
