使用c语言的动态内存分配的概念使允许C程序员在运行时分配内存。可以通过stdlib.h头文件的4个函数以c语言进行动态内存分配。
在学习上述函数之前,让我们了解静态内存分配和动态内存分配之间的区别。
静态内存分配 | 动态内存分配 |
---|---|
内存是在编译时分配的。 | 内存是在运行时分配的。 |
执行程序时不能增加内存。 | 可以在执行程序时增加内存。 |
用于数组。 | 用于链接列表。 |
现在让我们快速看一下用于动态内存分配的方法。
malloc() | 分配单个块的请求内存。 |
calloc() | 分配请求的内存的多个块。 |
realloc() | 重新分配malloc()或calloc()函数占用的内存。 |
free() | 释放动态分配的内存。 |
malloc()函数分配单个块的请求内存。它不会在执行时初始化内存,因此最初具有垃圾值,如果内存不足,则返回NULL。
ptr=(cast-type*)malloc(byte-size)
让我们看一下malloc()函数的示例。
链接:https://www.learnfk.comhttps://www.learnfk.com/c-programming/dynamic-memory-allocation-in-c.html
来源:LearnFk无涯教程网
#include<stdio.h> #include<stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //使用 malloc 分配的内存 if(ptr==NULL) { printf("Sorry! unable to allocate memory"); exit(0); } printf("Enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d",sum); free(ptr); return 0; }
输出
Enter elements of array: 3 Enter elements of array: 10 10 10 Sum=30
calloc()函数分配多个块的请求内存,最初将所有字节初始化为零,如果内存不足,则返回NULL。
calloc()函数的语法如下:
ptr=(cast-type*)calloc(number, byte-size)
让我们看一下calloc()函数的示例。
#include<stdio.h> #include<stdlib.h> int main(){ int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); //使用 malloc 分配的内存 if(ptr==NULL) { printf("Sorry! unable to allocate memory"); exit(0); } printf("Enter elements of array: "); for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d",sum); free(ptr); return 0; }
输出
Enter elements of array: 3 Enter elements of array: 10 10 10 Sum=30
如果内存不足以容纳malloc()或calloc(),则可以通过realloc()函数重新分配内存。简而言之,它会更改内存大小。
让我们看看realloc()函数的语法。
ptr=realloc(ptr, new-size)
必须通过调用free()函数释放由malloc()或calloc()函数占用的内存。否则,它将消耗内存,直到程序退出。
让我们看看free()函数的语法。
free(ptr)
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)