在C中使用realloc()

函数realloc用于调整之前由malloc或calloc分配的内存块的大小。

这是C语言中realloc的语法,

void *realloc(void *pointer, size_t size)

这里,

指针-通过malloc或calloc指向先前分配的内存块的指针。

大小-内存块的新大小。

这是realloc()C语言的示例,

示例

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) calloc(n, sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   p = (int*) realloc(p, 6);
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}

输出结果

Enter elements of array : 3 34 28 8
Sum : 73
Enter elements of array : 3 28 33 8 10 15
Sum : 145

在以上程序中,存储块由分配,calloc()并计算元素的总和。之后,realloc()将存储块的大小从4调整为6,然后计算它们的总和。

p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
   scanf("%d", p + i);
   s += *(p + i);
}