数据结构 预备知识
程序员文章站
2024-03-19 15:41:28
...
1.指针
指针的重要性:指针是C语言的灵魂
定义:
地址:内存单元的编号,从0开始的非负整数
指针:指针就是地址,地址就是指针;指针变量是存放内存单元地址的变量;指针的本质是一个操作受限的非负整数。
分类:基本类型的指针;指针和数组的关系
2.结构体
- 为什么会出现结构体:为了表示一些复杂的数据,而普通的基本类型变量无法满足要求;
- 定义:结构体是用户根据实际需要自己定义的复合数类型;
如何使用结构体
//定义结构体 struct Student { int sid; char name[200]; int age; };
//整体赋值,类似于Java中new类的构造函数
struct Student st = {1001,"zhangsan",18}; //单个赋值 st.sid=1001; strcpy(st.name,"zhangsan"); st.age=18;
//通常使用指针的方式赋值
struct Student *pst; //pst所指向的结构体变量中的sid这个成员 pst->sid=1001; strcpy(pst->name,"lisi"); pst->age=19;
注意事项:结构体变量不能算术计算,但是可以赋值;普通结构体变量和结构体指针变量作为函数传参的问题,推荐使用传递结构体指针的方式,这样效率高节约内存。
3.动态内存的分配和释放
一维数组: # include <stdio.h> # include <malloc.h> int main(void) { //静态分配数组 int a[5] = {2,3,5,6,9}; //len为一维数组的长度,可以根据需求动态分配长度 int len; printf("请输入你需要分配的数组长度:len="); scanf("%d",&len);//len=5 /* malloc为分配内存的函数,返回第一个字节的地址,但是默认返回是一个干地址,没有实际意义,必须加 强制类型转换为指定的指针类型才有意义,(int *)表示强转为int类型的指针,那么返回的地址指向的 就是第一个元素的地址,那么第二个元素的地址就是第一个地址向后挪一位 */ int * pArr = (int *)malloc(sizeof(int) * len); *pArr = 2;//类似于 a[0]=2,因为数组名就是指向了第一个元素的地址,跟*pArr一样 pArr[1] = 3; //类似于 a[1]=3 free(pArr);//把pArr所代表的动态分配的20个字节的内存释放 return 0; }
- 跨函数使用内存
# include <stdio.h> # include <malloc.h> struct Student { int sid; int age; }; struct Student * CreateStudent(void); void ShowStudent(struct Student *); int main(void) { struct Student * ps; ps = CreateStudent(); ShowStudent(ps); return 0; } void ShowStudent(struct Student * pst) { printf("%d %d",pst->sid,pst->age); } struct Student * CreateStudent(void) { struct Student * p = (struct Student *)malloc(sizeof(struct Student)); p->sid = 1001; p->age = 18; return p; }
- typedef函数的使用
typedef int INT; // 相当于给int起了一个别名 INT typedef struct Student { int sid; char name[100]; char sex; } ST; //ST st 就相当于 struct Student st,给struct Student 起了别名ST,这样简洁了代码 typedef struct Student { int sid; char name[100]; char sex; } * ST; //ST就相当于struct Student *
上一篇: Python 递归实现二分查找
下一篇: 线性查找与二分查找入门