C stdlib realloc() 函数
示例
增大已分配的内存
// Allocate memory for a number of items
int numItems = 10;
int *myArray = malloc(numItems * sizeof(int));
// Write into the memory
for(int i = 0; i < numItems; i++) {
myArray[i] = i + 1;
}
// Reallocate the memory
numItems = 20;
myArray = realloc(myArray, numItems * sizeof(int));
// Display the contents of the memory
for(int i = 0; i < numItems; i++) {
printf("%d ", myArray[i]);
}
// Free the memory
free(myArray);
myArray = NULL;
自己动手试一试 »
定义和用法
realloc()
函数会更改内存块的大小并返回指向该内存块的指针。如果当前位置没有足够的内存,则内存块将被移动到另一个位置并返回不同的指针。新分配内存中的值是不可预测的。
realloc()
函数定义在 <stdlib.h>
头文件中。
要了解更多关于内存分配的信息,请参阅我们的 C 内存管理教程。
语法
realloc(void * ptr, size_t size);
size_t
数据类型是一个非负整数。
参数值
参数 | 描述 |
---|---|
ptr | 指定一个要重新分配的内存块。 |
大小 | 指定内存块的新大小(以字节为单位)。 |
技术详情
返回 | 一个指向内存块的 void * 指针。 |
---|