首頁 > 後端開發 > C++ > 主體

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

WBOY
發布: 2023-08-28 12:41:05
轉載
1189 人瀏覽過

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
#include
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
登入後複製

以上是在C語言中,Realloc是什麼意思?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!