定义初始化和使用一个结构体

  1. #include <stdio.h>
  2. struct Data{
  3. int year;
  4. int month;
  5. int day;
  6. };
  7. struct Book{
  8. char title[128];
  9. char author[40];
  10. float price;
  11. struct Data date;
  12. char publisher[40];
  13. //结构体值初始化
  14. } book = {
  15. "凯凯BOOK",
  16. "凯凯",
  17. 99.9,
  18. {
  19. 2021,
  20. 11,
  21. 11
  22. },
  23. "武汉"
  24. };
  25. int main(){
  26. printf("书名: %s \n", book.title);
  27. printf("日期: %d-%d-%d \n", book.date.year, book.date.month, book.date.day);
  28. return 0;
  29. }

初始化方法 2

  1. #include <stdio.h>
  2. struct Data{
  3. int year;
  4. int month;
  5. int day;
  6. };
  7. struct Book{
  8. char title[128];
  9. char author[40];
  10. double price;
  11. struct Data date;
  12. char publisher[40];
  13. };
  14. int main(){
  15. // 初始化结构体内容
  16. struct Book book = {
  17. "APPLE",
  18. "凯凯",
  19. 99.9,
  20. {
  21. 2021,
  22. 11,
  23. 11
  24. },
  25. "武汉"
  26. };
  27. printf("书名: %s \n", book.title);
  28. printf("日期: %d-%d-%d \n", book.date.year, book.date.month, book.date.day);
  29. return 0;
  30. }

结构体数组

在初始化结构体的名称后面添加 [number] 即可定义一个结构体数组

  1. #include <stdio.h>
  2. struct Data {
  3. int year;
  4. int month;
  5. int day;
  6. };
  7. struct Book {
  8. char title[128];
  9. char author[40];
  10. double price;
  11. struct Data date;
  12. char publisher[40];
  13. };
  14. int main() {
  15. // 初始化结构体内容
  16. struct Book book[2] = {
  17. {
  18. "APPLE",
  19. "凯凯",
  20. 99.9,
  21. {
  22. 2021,
  23. 11,
  24. 11
  25. },
  26. "武汉"
  27. },
  28. {
  29. "KkBOOK",
  30. "KkBOOK",
  31. 99.9,
  32. {
  33. 2022,
  34. 12,
  35. 12
  36. },
  37. "KkBOOK"
  38. }
  39. };
  40. printf("书名: %s \n", book[1].title);
  41. printf("日期: %d-%d-%d \n", book[1].date.year, book[1].date.month, book[1].date.day);
  42. return 0;
  43. }

结构体指针

注意: 定义一个结构体指针和普通方式不一样 每个结构体都可以理解为一种类型 需要指定定义某个结构体类型的指针, 指向初始化后的对应结构体地址

  1. #include <stdio.h>
  2. struct Data {
  3. int year;
  4. int month;
  5. int day;
  6. };
  7. struct Book {
  8. char title[128];
  9. char author[40];
  10. double price;
  11. struct Data date;
  12. char publisher[40];
  13. } book = {
  14. "凯凯BOOK",
  15. "凯凯",
  16. 99.9,
  17. {
  18. 2021,
  19. 11,
  20. 11
  21. },
  22. "武汉"
  23. };;
  24. int main() {
  25. // 结构体指针
  26. // 定义一个 Book 类型的结构体指针, 指向初始化后的地址
  27. struct Book *pt = &book;
  28. // 访问结构体指针
  29. // 解引用的方式
  30. printf("title: %s \n", (*pt).title);
  31. // 箭头方式
  32. printf("author: %s \n", pt->author);
  33. return 0;
  34. }

访问结构体指针

  1. // 解引用的方式
  2. printf("title: %s \n", (*pt).title);
  3. // 箭头方式
  4. printf("author: %s \n", pt->author);