首頁  >  文章  >  後端開發  >  在C語言中,Realloc是什麼意思?

在C語言中,Realloc是什麼意思?

WBOY
WBOY轉載
2023-08-28 12:41:051296瀏覽

C函式庫的記憶體分配函數void *realloc(void *ptr, size_t size) 嘗試重新調整由ptr指向的先前使用malloc或calloc呼叫所分配的記憶體區塊。

記憶體分配函數

記憶體可以透過以下兩種方式進行分配:

在C語言中,Realloc是什麼意思?

#一旦在編譯時分配了內存,就無法在執行期間更改。要嘛記憶體不足,要嘛記憶體浪費。

解決方案是動態建立內存,即根據程式在執行期間的需求。

用於動態記憶體管理的標準函式庫函數如下:

  • 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&#39;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&#39;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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除