数据结构复习之C语言malloc()动态分配内存概述
2017-03-19 20:23
323 查看
#include <stdio.h> #include <malloc.h> int main(void) { int a[5] = {4, 10, 2, 8, 6}; // 计算数组元素个数 int len = sizeof(a)/sizeof(a[0]); int i; //printf("%d", len); // sizeof(int) int类型的字节数 // 动态分配内存 // malloc返回第一个字节的地址 int *pArr = (int *)malloc(sizeof(int) * len); for(i = 0; i < len;i++) scanf("%d", &pArr[i]); for(i = 0; i < len;i++) printf("%d\n", *(pArr + i)); free(pArr); // 把pArr所代表的动态分配的20个字节的内存释放 return 0; }
跨函数使用内存
函数内的局部变量,函数被调用完之后,变量内存就没有了。
如果是一个动态的变量,动态分配的内存必须通过free()进行释放,不然只有整个程序彻底结束的时候
才会释放。
跨函数使用内存实例:
#include <stdio.h> #include <malloc.h> struct Student { int sid; int age; }; struct Student *CreateStudent(void); int main(void) { struct Student *ps; ps = CreateStudent(); ShowStudent(ps); // 输出函数 return 0; } struct Student *CreateStudent(void) { // sizeof(struct Student) 结构体定义的数据类型所占用的字节数 struct Student *p = (struct Student *)malloc(sizeof(struct Student)); // 创建 // 赋值 p->sid = 99; p->age = 88; return p; }; void ShowStudent(struct Student *pst) { printf("%d %d\n", pst->sid, pst->age); }
相关文章推荐
- 复习(数据结构):图:c语言:邻接矩阵
- C语言 利用malloc()和realloc()动态分配内存
- 复习(数据结构):链表:c语言
- 复习(数据结构):图:c语言:邻接表
- C语言malloc()函数:动态分配内存空间
- 复习(数据结构):线性表 : C:动态分配内存
- C语言:动态分配内存,malloc()与realloc()区别
- 数据结构预热:malloc动态分配内存
- C语言:使用malloc()和calloc()动态分配内存
- 数据结构-2 C语言概述
- 复习(数据结构):栈:c语言:数组
- 复习(数据结构):栈:c语言:动态数组
- 【C语言和数据结构复习】序
- C语言复习 指针和动态分配内存
- 复习(数据结构):图:c语言:邻接矩阵DFS和BFS
- C语言复习 指针和动态分配内存
- C语言 利用malloc()和realloc()动态分配内存
- 复习(数据结构):队列:c语言
- 复习(数据结构):字符串:c语言
- 复习(数据结构):树:C语言