realloc() 函数在 stdlib.h 头文件中定义。它有助于重新调整之前使用 malloc() 或 calloc() 函数分配的指针所指向的内存块的大小。
void *realloc(void *ptr, size_t size); #where size should be a bytes
realloc() 函数接受两个参数。如果 ptr 为 NULL,则分配一个新的内存块并返回指向它的指针。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| ptr | 指向之前已分配且需要重新分配的内存块的指针 | 必需 |
| size | 内存块的新大小,以字节为单位 | 必需 |
如果 size 为 0 且 ptr 指向一个现有的内存块,则 ptr 所指向的内存块将被释放并返回一个 NULL 指针。
| 输入 | 返回值 |
|---|---|
| 成功 | 内存指针 |
| 失败 | NULL |
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s;
/*memory allocation */
s = (char *) malloc(12);
strcpy(s, "programming");
printf("String = %s, Address = %u\n", s, s);
/* Reallocating memory */
s = (char *) realloc(s, 20);
strcat(s, ".com");
printf("String = %s, Address = %u\n", s, s);
free(s);
return(0);
}
输出
String = programming, Address = 355090448 String = programming.com, Address = 355090448
#include <stdio.h>
#include <stdlib.h>
int main (){
int k, * p, t = 0;
p = malloc(200);
if (p == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
p = realloc(p,400);
if(p != NULL)
printf("Memory created successfully\n");
return 0;
}
输出
Memory created successfully