#include <stdlib.h>
void *realloc( void *ptr, size_t size );
函数将 ptr 对象的储存空间改变为给定的大小 size。参数 size 可以是任意大小,大于或小于原尺寸都可以。返回值是指向新空间的指针,如果错误发生返回 NULL。
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char *str; /* allocate memory for string */ str = malloc(10); /* copy "Hello" into string */ strcpy(str, "Hello"); printf("String is %s\n Address is %p\n", str, str); str = realloc(str, 20); printf("String is %s\n New address is %p\n", str, str); /* free memory */ free(str); return 0; }
输出结果:
String is Hello Address is 0000000000A21410 String is Hello New address is 0000000000A21410