可以使用realloc()更改动态分配内存的大小。
null
根据C99标准:
void * realloc ( void *ptr, size_t size); |
realloc解除分配ptr指向的旧对象,并返回一个指针,指向大小由size指定的新对象。新对象的内容与解除分配前的旧对象的内容相同,新对象和旧对象的大小以较小者为准。新对象中超出旧对象大小的任何字节都有不确定的值。
需要注意的是 realloc()只能用于动态分配的内存 .如果未动态分配内存,则行为未定义。 例如,程序1演示了realloc()的错误使用,程序2演示了realloc()的正确使用。
项目1:
#include <stdio.h> #include <stdlib.h> int main() { int arr[2], i; int *ptr = arr; int *ptr_new; arr[0] = 10; arr[1] = 20; // incorrect use of new_ptr: undefined behaviour ptr_new = ( int *) realloc (ptr, sizeof ( int )*3); *(ptr_new + 2) = 30; for (i = 0; i < 3; i++) printf ( "%d " , *(ptr_new + i)); getchar (); return 0; } |
输出: 未定义的行为
项目2:
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = ( int *) malloc ( sizeof ( int )*2); int i; int *ptr_new; *ptr = 10; *(ptr + 1) = 20; ptr_new = ( int *) realloc (ptr, sizeof ( int )*3); *(ptr_new + 2) = 30; for (i = 0; i < 3; i++) printf ( "%d " , *(ptr_new + i)); getchar (); return 0; } |
输出: 10 20 30
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END