C realloc() function
C realloc() function - Reallocate memory blocks
Syntax realloc() function
void *realloc(void *ptr, size_t size)
The realloc() function is used to change the size of a previously reserved storage block. The ptr argument points to the beginning of the block. The size argument gives the new size of the block, in bytes.
If the ptr is NULL, realloc() reserves a block of storage of size bytes. It does not necessarily give all bits of each element an initial value of 0.
If size is 0 and the ptr is not NULL, realloc()frees the storage allocated to ptr and returns NULL
Parameters realloc() function
Name | Description | Required /Optional |
---|---|---|
ptr | Pointer to previously allocated memory block. | Required |
size | New size in bytes. | Required |
Return value from realloc()
- Returns a pointer to the newly allocated memory.
- If size is 0, the realloc() function returns NULL.
Example: realloc() function
The following example shows the usage of realloc() function.
#include<stdio.h>
//To use realloc in our program
#include<stdlib.h>
int main()
{
int *ptr,i;
//allocating memory
ptr = malloc(sizeof(int));
ptr[0] = 10;
ptr[1] = 20;
//realloc memory size
ptr = realloc(ptr, 3 * sizeof(int));
ptr[2] = 300;
ptr[3] = 400;
ptr[4] = 500;
//printing values
for(i = 0; i <= 4; i++)
printf("%d\n",ptr[i]);
return 0;
}
Output:
10 20 300 400 500
C Programming Code Editor:
Previous C Programming: C malloc()
Next C Programming: C abort()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming/stdlib/c-realloc.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics