C语言中的realloc是什么?


C 库内存分配函数 void *realloc(void *ptr, size_t size) 尝试重新调整由 ptr 指向的内存块的大小,该内存块之前已通过调用 malloc 或 calloc 分配。

内存分配函数

内存可以以两种方式分配,如下所述:

一旦在编译时分配了内存,就不能在执行期间更改它。这将导致内存不足或内存浪费的问题。

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

用于动态内存管理的标准库函数如下:

  • 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
");    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 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

更新于: 2021年3月17日

577 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.