C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Reallocate array using realloc() function

C Program: Reallocate array using realloc() function

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int *arr;

    int n, newSize, i;

 

    // Step 1: Allocate initial memory using malloc()

    printf("Enter initial number of elements: ");

    scanf("%d", &n);

 

    arr = (int*) malloc(n * sizeof(int));

    if (arr == NULL) {

        printf("Memory allocation failed!\n");

        return 1;

    }

 

    // Step 2: Input elements

    printf("\nEnter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        printf("Element %d: ", i + 1);

        scanf("%d", &arr[i]);

    }

 

    // Display original array

    printf("\nOriginal array elements:\n");

    for (i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

 

    // Step 3: Reallocate memory

    printf("\n\nEnter new size of array: ");

    scanf("%d", &newSize);

 

    arr = (int*) realloc(arr, newSize * sizeof(int));

    if (arr == NULL) {

        printf("Memory reallocation failed!\n");

        return 1;

    }

 

    // Step 4: If array size increased, take new inputs

    if (newSize > n) {

        printf("\nEnter %d new elements:\n", newSize - n);

        for (i = n; i < newSize; i++) {

            printf("Element %d: ", i + 1);

            scanf("%d", &arr[i]);

        }

    }

 

    // Step 5: Display updated array

    printf("\nUpdated array elements:\n");

    for (i = 0; i < newSize; i++) {

        printf("%d ", arr[i]);

    }

 

    // Step 6: Free memory

    free(arr);

    printf("\n\nMemory has been freed successfully.\n");

 

    return 0;

}

Output

 
OUTPUT :
Enter initial number of elements: 3

Enter 3 elements:
Element 1: 10
Element 2: 20
Element 3: 30

Original array elements:
10 20 30

Enter new size of array: 5

Enter 2 new elements:
Element 4: 40
Element 5: 50

Updated array elements:
10 20 30 40 50

Memory has been freed successfully.

Explanation

Step

Description

malloc(n * sizeof(int))

Allocates memory for n integers.

realloc(arr, newSize * sizeof(int))

Resizes the previously allocated memory block.

realloc()

Keeps existing data intact up to the smaller of the old or new size.

free(arr)

Releases the allocated memory.