1.1 结构体

1.1 如何使用结构体

两种方式:
struct Student st = {1000,”zhangshan”,20};
struct Student pst = &st;
方式一:st.sid;
方式二:pst->sid;(pst->sid = (
(&st)).sid)

  1. #include <stdio.h>
  2. #include <string.h>
  3. #pragma warning(disable:4996)//strcpy不安全忽略
  4. struct Student
  5. {
  6. char name[20];
  7. int age;
  8. int high;
  9. };
  10. void PrintStruct(struct Student*);//打印结构体中的成员
  11. int main()
  12. {
  13. struct Student st = { "xiaozhao",24,175 };
  14. PrintStruct(&st);
  15. }
  16. void PrintStruct(struct Student* pst)
  17. {
  18. pst->age = 23;
  19. pst->high = 180;
  20. strcpy(pst->name,"xiaozhaotongxue");
  21. printf("%s,%d,%d", pst->name, pst->age, pst->high);
  22. }

1.2 注意事项

结构体变量不能加减乘除,但可以相互赋值。
普通结构体变量和结构体指针变量作为函数传参问题。

1.2动态内存分配malloc()

image.png

  1. #include <stdio.h>
  2. #include "malloc.h" //解决malloc无法识别
  3. #pragma warning(disable:4996)
  4. int main()
  5. {
  6. int len = 0;
  7. printf("请输入您需要分配的数组的长度:len:");
  8. scanf("%d", &len);
  9. int *pArr = (int *)malloc(sizeof(int) * len);
  10. //为什么要强制转换
  11. //malloc返回的是void* 需要强制转换成所需要的指针类型,干地址。
  12. //malloc返回的是第一个“字节”的地址,第一个“字节”地址占多少字节无法确认,需要强制转换。
  13. *pArr = 4;//pArr[0]=4
  14. pArr[1] = len;
  15. printf("%d\n", pArr[1]);
  16. for (int i = 0; i < len; i++)
  17. {
  18. pArr[i] = i;
  19. printf("%d\n", pArr[i]);
  20. }
  21. free(pArr);//把pArr所代表的动态分配的20个字节内存释放
  22. }

1.3 跨函数使用内存

image.png
malloc申请动态空间,返回的是void*,所以需要强制转换,malloc申请的是结构体模板的空间,下面程序申请两个int(age,sdi)内存空间。

  1. #include <stdio.h>
  2. #include <malloc.h>
  3. struct Student
  4. {
  5. int age;
  6. int sdi;
  7. };
  8. struct Student* CreateMalloc(void);
  9. void ShowPst(struct Student*);
  10. int main()
  11. {
  12. struct Student *pst = NULL;
  13. pst = CreateMalloc();
  14. ShowPst(pst);
  15. }
  16. struct Student* CreateMalloc(void)
  17. {
  18. struct Student* pst = (struct Student*)malloc(sizeof(struct Student));//动态申请内存
  19. pst->age = 24;
  20. pst->sdi = 10;
  21. return pst;
  22. }
  23. void ShowPst(struct Student* pst)
  24. {
  25. printf("%d,%d", pst->age, pst->sdi);
  26. free(pst);
  27. }