C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C语言动态内存分配

C语言中动态内存分配的概念 使C程序员可以在运行时分配内存。通过stdlib.h头文件的4个功能可以用c语言进行动态内存分配。
malloc() calloc() realloc() free()
在学习上述功能之前,让我们了解静态内存分配和动态内存分配之间的区别。
静态内存分配 动态内存分配
内存是在编译时分配的。 内存是在运行时分配的。
执行程序时不能增加内存。 可以在执行程序时增加内存。
用于数组。 用于链接列表。
现在让我们快速了解一下用于动态内存分配的方法。
malloc() 分配单个块的请求内存。
calloc() 分配请求的内存的多个块。
realloc() 重新分配malloc()或calloc()函数占用的内存。
free() 释放动态分配的内存。

C语言中的malloc()函数

malloc()函数分配单个块的请求内存。
它不会初始化内存在执行时,因此它最初具有垃圾值。
如果内存不足,则返回NULL。
malloc()函数的语法如下:
ptr=(cast-type*)malloc(byte-size)
让我们看一下malloc()函数的示例。
#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));  //memory allocated using 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

c中的calloc()函数

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));  //memory allocated using calloc  
    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

realloc()函数

如果内存不足以容纳malloc()或calloc(),则可以通过realloc()函数重新分配内存。简而言之,它会更改内存大小。
让我们看看realloc()函数的语法。
ptr=realloc(ptr, new-size)

free()函数

必须通过调用free()函数释放malloc()或calloc()函数所占用的内存。否则,它将消耗内存,直到程序退出。
让我们看看free()函数的语法。
free(ptr)

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4