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;
}