VR Indian Wanderers Youtube RSS Feed
Learn with Vikas Suhag
Dynamic memory re-allocation in C Language using realloc() function
Mar 06, 2022   Vikas Suhag

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;     // This pointer will hold the
int n, i;    // Get the number of elements for the array
n = 5;
ptr = (int*)calloc(n, sizeof(int));

if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else  // Memory has been successfully allocated
    {
    printf("Memory successfully allocated using calloc.\n");
    
    for (i = 0; i < n; ++i) // Get the elements of the array
    {     
    ptr[i] = i + 1;     
    }
    
    // Print the elements of the array
    printf("The elements of the array are: ");
    for (i = 0; i < n; ++i) {
    
    printf("%d, ", ptr[i]);
    }
    // Get the new size for the array
    n = 10;
    printf("\n\nEnter the new size of the array: %d\n", n); // Dynamically re-allocate memory using realloc()
    ptr = (int*)realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated
    printf("Memory successfully re-allocated using realloc.\n"); // Get the new elements of the array
    for (i = 5; i < n; ++i) {
    ptr[i] = i + 1;
    } // Print the elements of the array
    printf("The elements of the array are: ");
    for (i = 0; i < n; ++i) {
    printf("%d, ", ptr[i]);
    }
    free(ptr);
    }
return 0;
}


Leave a Comment

* Email will not be published.
All comments are only visible after approval.
Most Viewed articles
Travel Blog - VR Indian Wanderers
VR Indian Wanderers
Govt. Jobs Portal
Govt. Jobs Portal
Free Chart Maker
Make free animated Charts from .CSV
Search
Youtube Channel
Podcast
Subscribe to Email Updates
Connect With Us
VR Indian Wanderers Youtube RSS Feed
© 2024 Learn with Vikas Suhag. All Rights Reserved.