Welcome to our deep dive into the realloc() function in C programming! In this lesson, we'll explore the realloc() function, its purpose, and how to use it effectively. By the end of this lesson, you'll be able to manage dynamic memory allocation like a pro! 💡
realloc()? 📝In C programming, realloc() is a library function that changes the size of an array or a dynamically allocated memory block and moves it, if necessary, to a new location.
realloc()? 📝void *realloc(void *ptr, size_t size);ptr: the pointer to the memory block you want to resizesize: the new size of the memory block#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, i;
int arr_size = 5;
// Allocate memory for an array of size 5
arr = (int *)malloc(arr_size * sizeof(int));
// Fill the array
for(i = 0; i < arr_size; i++)
arr[i] = i * i;
// Check if the array is filled correctly
for(i = 0; i < arr_size; i++)
printf("arr[%d] = %d\n", i, arr[i]);
// Increase the array size by 2
arr_size += 2;
// Reallocate memory for the larger array
arr = (int *)realloc(arr, arr_size * sizeof(int));
// Fill the newly allocated elements
for(; i < arr_size; i++)
arr[i] = i * i;
// Check if the array is filled correctly
for(i = 0; i < arr_size; i++)
printf("arr[%d] = %d\n", i, arr[i]);
return 0;
}#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, i;
int arr_size = 10;
// Allocate memory for an array of size 10
arr = (int *)malloc(arr_size * sizeof(int));
// Fill the array
for(i = 0; i < arr_size; i++)
arr[i] = i * i;
// Check if the array is filled correctly
for(i = 0; i < arr_size; i++)
printf("arr[%d] = %d\n", i, arr[i]);
// Decrease the array size to 5
arr_size = 5;
// Reallocate memory for the smaller array
arr = (int *)realloc(arr, arr_size * sizeof(int));
// Check if the array is correctly resized
printf("After reallocating, the size is: %ld\n", sizeof(arr) / sizeof(int));
return 0;
}What is the purpose of the `realloc()` function in C programming?
That's it for our deep dive into the realloc() function in C programming! With a good understanding of dynamic memory management and the realloc() function, you can now create more efficient and robust C programs. Happy coding! 💡