C stdlib realloc() 函式
示例
增大已分配的記憶體
// Allocate memory for a number of items
int numItems = 10;
int *myArray = malloc(numItems * sizeof(int));
// Write into the memory
for(int i = 0; i < numItems; i++) {
myArray[i] = i + 1;
}
// Reallocate the memory
numItems = 20;
myArray = realloc(myArray, numItems * sizeof(int));
// Display the contents of the memory
for(int i = 0; i < numItems; i++) {
printf("%d ", myArray[i]);
}
// Free the memory
free(myArray);
myArray = NULL;
自己動手試一試 »
定義和用法
realloc()
函式會更改記憶體塊的大小並返回指向該記憶體塊的指標。如果當前位置沒有足夠的記憶體,則記憶體塊將被移動到另一個位置並返回不同的指標。新分配記憶體中的值是不可預測的。
realloc()
函式定義在 <stdlib.h>
標頭檔案中。
要了解更多關於記憶體分配的資訊,請參閱我們的 C 記憶體管理教程。
語法
realloc(void * ptr, size_t size);
size_t
資料型別是一個非負整數。
引數值
引數 | 描述 |
---|---|
ptr | 指定一個要重新分配的記憶體塊。 |
大小 | 指定記憶體塊的新大小(以位元組為單位)。 |
技術詳情
返回 | 一個指向記憶體塊的 void * 指標。 |
---|