當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C語言 realloc用法及代碼示例


C語言stdlib頭文件(stdlib.h)中realloc函數的用法及代碼示例。

用法:

void* realloc (void* ptr, size_t size);
重新分配內存塊
更改由指向的內存塊的大小ptr

該函數可以將存儲塊移動到新的位置(其地址由該函數返回)。

即使將存儲塊移動到新位置,該存儲塊的內容也會保留到新舊大小中的較小者。如果是新的size較大,則新分配部分的值不確定。

萬一ptr是一個空指針,該函數的行為類似於malloc,分配一個新的size個字節,並返回指向其開頭的指針。

否則,如果size為零,先前分配在的內存ptr被釋放,就像對free做了,並且空指針返回。
如果size為零,則返回值取決於特定的庫實現:它可以是空指針或其他不應取消引用的位置。

如果函數未能分配所請求的內存塊,則返回空指針,並使用參數指向該內存塊ptr未取消分配(它仍然有效,並且內容不變)。

參數

ptr
指向先前分配有一個內存塊的指針malloccalloc或者realloc
或者,這可以是空指針,在這種情況下,將分配一個新塊(就像malloc被稱為)。
size
內存塊的新大小,以字節為單位。
size_t是無符號整數類型。

返回值

指向重新分配的內存塊的指針,該指針可以與ptr或新位置。
該指針的類型是void*,可以將其強製轉換為所需的數據指針類型,以便將其取消引用。

示例

/* realloc example: rememb-o-matic */
#include <stdio.h>      /* printf, scanf, puts */
#include <stdlib.h>     /* realloc, free, exit, NULL */

int main ()
{
  int input,n;
  int count = 0;
  int* numbers = NULL;
  int* more_numbers = NULL;

  do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;

     more_numbers = (int*) realloc (numbers, count * sizeof(int));

     if (more_numbers!=NULL) {
       numbers=more_numbers;
       numbers[count-1]=input;
     }
     else {
       free (numbers);
       puts ("Error (re)allocating memory");
       exit (1);
     }
  } while (input!=0);

  printf ("Numbers entered: ");
  for (n=0;n<count;n++) printf ("%d ",numbers[n]);
  free (numbers);

  return 0;
}


程序會提示用戶輸入數字,直到輸入零字符為止。每次引入新值時,數字所指向的存儲塊都會增加int



相關用法


注:本文由純淨天空篩選整理自C標準庫大神的英文原創作品 C realloc function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。