总结
豆包 AI 助手文章总结
首页 > 后端开发 > C++ > 正文

在C语言中,Realloc是什么意思?

WBOY
发布: 2023-08-28 12:41:05
转载
1816人浏览过

c库的内存分配函数void *realloc(void *ptr, size_t size) 尝试重新调整由ptr指向的先前使用malloc或calloc调用分配的内存块。

内存分配函数

内存可以通过以下两种方式进行分配:

在C语言中,Realloc是什么意思?

一旦在编译时分配了内存,就无法在执行期间更改。要么内存不足,要么内存浪费。

解决方案是动态创建内存,即根据程序在执行期间的需求。

立即学习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<stdio.h>
#include<stdlib.h>
int main(){
   int *ptr, i, num;
   printf("array size is 5</p><p>");
   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("</p><p>Let's increase the array size to 7</p><p> ");
   ptr = (int*)realloc(ptr, 7 * sizeof(int));
   if(ptr==NULL){
      printf("Memory allocation failed");
      exit(1); // exit the program
   }
   printf("</p><p> enter 2 more integers</p><p></p><p>");
   for(i = 5; i < 7; i++){
      printf("Enter element number at %d: ", i);
      scanf("%d", ptr+i);
   }
   printf("</p><p> result array is: </p><p></p><p>");
   for(i = 0; i < 7; i++){
      printf("%d ", *(ptr+i) );
   }
   return 0;
}
登录后复制

输出

当上述程序被执行时,它产生以下结果 −

array size is 5
enter number at 0: 23
enter number at 1: 12
enter number at 2: 45
enter number at 3: 67
enter number at 4: 20
Let's increase the array size to 7
enter 2 more integers
Enter element number at 5: 90
Enter element number at 6: 60
result array is:
23 12 45 67 20 90 60
登录后复制

以上就是在C语言中,Realloc是什么意思?的详细内容,更多请关注php中文网其它相关文章!

C语言速学教程(入门到精通)
C语言速学教程(入门到精通)

C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号