动态内存分配

本文介绍了C语言中动态分配及释放内存的方法,包括malloc、calloc、realloc和free函数的使用。通过实例展示了如何利用这些函数求解平均分,涵盖了内存分配、读取输入、计算平均值到释放内存的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态分配以及destroy内存的函数
Function NmaeDescription
malloc()按需求分配指定大小的内存,如果空间不够,返回void 数据类型, 或者NULL
calloc()分配一块指定大小的空间并且初始化为0,如果空间不够,返回NULL
feallloc()改变之前分配的大小,如果新的地址比之前的大,多出来的那一部分没有被初始化,之前所分配的内存其中内容也不变,反之,新的大小里面的内容不变
free()释放一块内存,这块内存的首地址作为参数传递给函数

 

举个例子,求平均分。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int numgrades, i, sum;
    int *grades;
    
    printf("\nEnter the number of grades to be processed: ");
    scanf("%d", &numgrades);
    
    /* here is where the request for memory is made */
    grades = (int *) malloc(numgrades * sizeof(int));
    /* here we check that the allocation was satisfied */
    if (grades == (int *) NULL)
    {
               printf("nFailed to allocated grades array\n");
               exit(1);
    }
    
    for (i = 0; i < numgrades; i++)
    {
        printf(" Enter a grades: ");
        scanf("%d", &grades[i]);
    }
    
    printf("\nAn array was created for %d integers", numgrades);
    printf("\nThe average score you entered  are:\n");
    
    for (i = 0; i < numgrades; i++)
    {
    sum += grades[i];
    }
    printf(" %d\n", sum/numgrades);
   
    system("pause");
    free(grades);
    
    return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值