准备工作之动态内存分配[基于郝斌课程]
定义一块内存可以用数组定义,也可以动态分配:使用数组定义一块内存,则该块内存是静态的,也就是一旦定义之后,这块内存的大小就固定了,例如,数组元素个数是5,则定义后,这=这块内存大小就是5,不能再改变
但是用malloc动态分配的话,这块内存的大小就由我们自己来定义了,例如定义大小为5的内存块,使用完毕后,需要一个大小为3的内存块,就可以先使用malloc来定义一个大小为3的内存块,如何使用free来释放此块内存,之后再次使用malloc来定义大小为3的内存块,最后需要用free来释放该块内存
/*
@file main.c
@brief 数据结构预备知识之动态内存分配
@author EricsT (EricsT@163.com)
@version v1.0.0
@date 2025-09-20
@history 2025-09-20 EricsT - 新建文件
*/
#include <stdio.h>
#include <malloc.h>
int main(void)
{
int a = { 4, 10, 2, 8, 6 };
int len;
printf("请输入您需要分配的数组长度:len = ");
scanf("%d", &len);
//malloc函数只返回首字节地址
int* ptr = (int*)malloc(sizeof(int) * len);//分配内存
*ptr = 4;//类似于a = 4
*(ptr + 1) = 10;//类似于a = 10;
ptr = 2;//类似于a = 2;
printf("%d %d %d\n\n\n", ptr, ptr, ptr);
for (int i = 0; i < len; ++i)
scanf("%d", ptr + i);
for (int i = 0; i < len; ++i)
printf("%d\n", ptr);
free(ptr);//释放内存
return 0;
}在以下程序中,调用了 f() 函数时, j 所占内存是存在的,当 f() 函数调用结束后, j 所占的内存就不合法了,因为 j 是一个局部变量
/*
@file main.c
@brief 数据结构预备知识之动态内存分配
@author EricsT (EricsT@163.com)
@version v1.0.0
@date 2025-09-20
@history 2025-09-20 EricsT - 新建文件
*/
#include <stdio.h>
int f();
int main(void)
{
int i = 10;
i = f();
printf("i = %d\n", i);
return 0;
}
int f()
{
int j = 20;
return j;
}在以下程序中,掉用函数结束后,ptr都可以指向合法的内存块
/*
@file main.c
@brief 数据结构预备知识之跨函数使用内存
@author EricsT (EricsT@163.com)
@version v1.0.0
@date 2025-09-20
@history 2025-09-20 EricsT - 新建文件
*/
#include<stdio.h>
#include <malloc.h>
void fun(int** p);
int main(void)
{
int* p;
fun(&p);
//调用完之后,p就指向合法的内存块
return 0;
}
void fun(int** p)
{
*p = (int*)malloc(4);//手动分配,不释放就会一直被占用
}/*
@file main.c
@brief 数据结构预备知识之跨函数使用内存
@author EricsT (EricsT@163.com)
@version v1.0.0
@date 2025-09-20
@history 2025-09-20 EricsT - 新建文件
*/
#include <stdio.h>
#include <malloc.h>
struct Student
{
int sid;
int age;
};
Student* CreatStudent(void);
void ShowStudent(Student* ptrStu);
int main(void)
{
Student* ptrStu;//占4个字节
//Student std;//占8个字节,所以采用指针操作
ptrStu = CreatStudent();
ptrStu->age = 10;
ptrStu->sid = 99;
ShowStudent(ptrStu);
return 0;
}
Student* CreatStudent(void)
{
return (Student*)malloc(sizeof(Student));
}
void ShowStudent(Student* ptrStu)
{
printf("%d %d\n", ptrStu->age, ptrStu->sid);
}
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]