c库的内存分配函数void *realloc(void *ptr, size_t size) 尝试重新调整由ptr指向的先前使用malloc或calloc调用分配的内存块。
内存分配函数
内存可以通过以下两种方式进行分配:

一旦在编译时分配了内存,就无法在执行期间更改。要么内存不足,要么内存浪费。
解决方案是动态创建内存,即根据程序在执行期间的需求。
立即学习“C语言免费学习笔记(深入)”;
用于动态内存管理的标准库函数如下:
malloc ( )calloc ( )realloc ( )free ( )
realloc ( )函数
用于重新分配已经分配的内存。
可以减少或增加已分配的内存。
返回一个指向重新分配内存的基地址的void指针。
realloc()函数的语法如下:
Free void *realloc (pointer, newsize);
示例
以下示例展示了realloc()函数的用法。
int *ptr;ptr = (int * ) malloc (1000);// we can use calloc also- - -- - -- - -ptr = (int * ) realloc (ptr, 500);- - -- - -ptr = (int * ) realloc (ptr, 1500);
示例
下面是使用realloc()函数的C程序:
在线演示
#include#includeint main(){ int *ptr, i, num; printf("array size is 5"); ptr = (int*)calloc(5, sizeof(int)); if(ptr==NULL){ printf("Memory allocation failed"); exit(1); // exit the program } for(i = 0; i < 5; i++){ printf("enter number at %d: ", i); scanf("%d", ptr+i); } printf("
Let's increase the array size to 7
"); ptr = (int*)realloc(ptr, 7 * sizeof(int)); if(ptr==NULL){ printf("Memory allocation failed"); exit(1); // exit the program } printf("
enter 2 more integers
"); for(i = 5; i < 7; i++){ printf("Enter element number at %d: ", i); scanf("%d", ptr+i); } printf("
result array is:
"); for(i = 0; i < 7; i++){ printf("%d ", *(ptr+i) ); } return 0;}
输出
当上述程序被执行时,它产生以下结果 −
array size is 5enter number at 0: 23enter number at 1: 12enter number at 2: 45enter number at 3: 67enter number at 4: 20Let's increase the array size to 7enter 2 more integersEnter element number at 5: 90Enter element number at 6: 60result array is:23 12 45 67 20 90 60
以上就是在C语言中,Realloc是什么意思?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1443896.html
微信扫一扫
支付宝扫一扫