Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use of realloc() in C
The function realloc is used to resize the memory block which is allocated by malloc or calloc before.
Here is the syntax of realloc in C language,
void *realloc(void *pointer, size_t size)
Here,
pointer − The pointer which is pointing the previously allocated memory block by malloc or calloc.
size − The new size of memory block.
Here is an example of realloc() in C language,
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
p = (int*) realloc(p, 6);
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
return 0;
}
Output
Enter elements of array : 3 34 28 8 Sum : 73 Enter elements of array : 3 28 33 8 10 15 Sum : 145
In the above program, The memory block is allocated by calloc() and sum of elements is calculated. After that, realloc() is resizing the memory block from 4 to 6 and calculating their sum.
p = (int*) realloc(p, 6);
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}Advertisements