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()
C Programming: Tips of the Day
What's the point of const pointers?
const is a tool which you should use in pursuit of a very important C++ concept:
Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.
Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:
void foo(int* ptr) { ptr = 0;// oops, I meant *ptr = 0 }
If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.
Ref : https://bit.ly/33Cdn3Q
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises