动态内存分配

1.malloc

        函数原型:void *malloc(size_t size);

        功能:分配一块至少为size字节的内存区域

2.calloc

        函数原型:void *calloc(size_t num, size_t size);

        功能:分配一块总大小为num * size 字节的内存区域并初始化为0

3.realloc

        函数原型:void *realloc(void *ptr, size_t newsize);

        功能:更改之前通过malloc或calloc分配的内存块大小

4.应用实例

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

int main() {
    int* array;
    int num_elements = 5;
    int new_elements = 10;

    //使用malloc分配内存
    array = (int*)malloc(num_elements * sizeof(int));
    if (array == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return 1;
    }

    //初始化分配的内存
    for (int i = 0; i < num_elements; i++) {
        array[i] = i * 2;
    }

    //打印数组内容
    printf("原始数组:");
    for (int i = 0; i < num_elements; i++) {
        printf("%d", array[i]);
    }
    printf("\n");

    //使用realloc扩展内存
    array = (int*)realloc(array, new_elements * sizeof(int));
    if (array == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return 1;
    }

    //填充新元素
    for (int i = num_elements; i < new_elements; i++) {
        array[i] = i * 2;
    }

    //打印扩展后的数组
    printf("扩展后的数组:");
    for (int i = 0; i < new_elements; i++) {
        printf("%d", array[i]);
    }
    printf("\n");

    //释放分配的内存
    free(array);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值