1.1 结构体
1.1 如何使用结构体
两种方式:
struct Student st = {1000,”zhangshan”,20};
struct Student pst = &st;
方式一:st.sid;
方式二:pst->sid;(pst->sid = ((&st)).sid)
#include <stdio.h>#include <string.h>#pragma warning(disable:4996)//strcpy不安全忽略struct Student{char name[20];int age;int high;};void PrintStruct(struct Student*);//打印结构体中的成员int main(){struct Student st = { "xiaozhao",24,175 };PrintStruct(&st);}void PrintStruct(struct Student* pst){pst->age = 23;pst->high = 180;strcpy(pst->name,"xiaozhaotongxue");printf("%s,%d,%d", pst->name, pst->age, pst->high);}
1.2 注意事项
结构体变量不能加减乘除,但可以相互赋值。
普通结构体变量和结构体指针变量作为函数传参问题。
1.2动态内存分配malloc()

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

malloc申请动态空间,返回的是void*,所以需要强制转换,malloc申请的是结构体模板的空间,下面程序申请两个int(age,sdi)内存空间。
#include <stdio.h>#include <malloc.h>struct Student{int age;int sdi;};struct Student* CreateMalloc(void);void ShowPst(struct Student*);int main(){struct Student *pst = NULL;pst = CreateMalloc();ShowPst(pst);}struct Student* CreateMalloc(void){struct Student* pst = (struct Student*)malloc(sizeof(struct Student));//动态申请内存pst->age = 24;pst->sdi = 10;return pst;}void ShowPst(struct Student* pst){printf("%d,%d", pst->age, pst->sdi);free(pst);}
