C 語言中 realloc() 的使用


realloc 函式用於修改之前由 malloc 或 calloc 分配的記憶體塊大小。

以下是 C 語言中 realloc 的語法:

void *realloc(void *pointer, size_t size)

其中,

指標 - 指向之前由 malloc 或 calloc 分配的記憶體塊的指標。

size - 新的記憶體塊大小。

以下是 C 語言中 realloc() 的示例:

示例

 線上演示

#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("
Error! memory not allocated.");       exit(0);    }    printf("
Enter elements of array : ");    for(i = 0; i < n; ++i) {       scanf("%d", p + i);       s += *(p + i);    }    printf("
Sum : %d", s);    p = (int*) realloc(p, 6);    printf("
Enter elements of array : ");    for(i = 0; i < n; ++i) {       scanf("%d", p + i);       s += *(p + i);    }    printf("
Sum : %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("
Enter elements of array : "); for(i = 0; i < n; ++i) {    scanf("%d", p + i);    s += *(p + i); }

更新於: 2020-6-26

1.1 萬+ 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

快速入門
廣告
© . All rights reserved.