栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

指针和动态内存——malloc calloc realloc free

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

指针和动态内存——malloc calloc realloc free

1、malloc

void* p=malloc(size_t size)

eg:void *p=malloc(3*sizeof(int))

括号里面的参数为:单元的数量*每个单元的字节数

malloc返回的一个void指针,无法直接解引用(不能解引用一个void指针)

通常我们需要把它转换成一个特定类型指针:

int *p=(int *)malloc(3*sizeof(int))             //创建了一个含有三个元素的数组

print p

*p=2;

*(p+1)=3;

*(p+2)=6;

2、calloc

void* calloc(size_t num,size_t size)

eg:int *p=(int *)calloc(3,sizeof(int))

与malloc区别:

(1)calloc接受两个参数,第一个参数是数量,第二个参数是类型大小

(2)malloc分配完内存后,不会对前期进行初始化,如果没有填入值,会得到一些垃圾

而calloc会初始化为0

让我们写一个程序来验证第二个区别:

#include
#include

int main()
{
    int n;
    printf("enter the size of the array:");
    scanf("%d",&n);
    int *A=(int*)malloc(n*sizeof(int));
//    int *A=(int*)calloc(n,sizeof(int));

    for(int i=0;i 

3、realloc

void* realloc(void* ptr,size_t size)

使用方法:有一块内存,动态分配的内存,想修改内存块大小。

第一个参数表示已分配的起始地址的指针,第二个参数代表新的内存快大小

(应用于不同的场景)

eg:

int *B=(int*)realloc(A,2*n*sizeof(int));

这个函数会请求一个新的大小是2n的内存,然后把之前那个内存块的内容拷贝过去,如果新的内存块大小更大,如果可以扩展之前的块,如果能在之前的块的基础上找到连续的内存,那么扩展之前的块,否则分配新的内存。把之前的块的内容拷贝过去,然后释放之前的内存。

让我们来看看一个realloc的使用例子:

#include
#include

int main()
{
    int n;
    printf("enter the size of the array:");
    scanf("%d",&n);
    int *A=(int*)malloc(n*sizeof(int));//int *A=(int*)calloc(n,sizeof(int));
    for(int i=0;i 

4、free

free用于释放调用的内存

比如:

#include
#include

int main()
{
    int n;
    printf("enter the size of the array:");
    scanf("%d",&n);
    int *A=(int*)malloc(n*sizeof(int));//如果calloc:int *A=(int*)calloc(n,sizeof(int));
    for(int i=0;i 

这时我们运行会出现什么呢?

 

 当我们在free函数后面重新加上一个赋值语句:

#include
#include

int main()
{
    int n;
    printf("enter the size of the array:");
    scanf("%d",&n);
    int *A=(int*)malloc(n*sizeof(int));//如果calloc:int *A=(int*)calloc(n,sizeof(int));
    for(int i=0;i 

这时运行:

 我们可以看到,数组A[2]被重新赋值

以上就是关于指针和动态内存的四个函数的内容了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/604906.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号