C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic array resizing at runtime

C Program: Dynamic array resizing at runtime

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int *arr;

    int size, newSize;

    int i;

 

    // Step 1: Initial allocation

    printf("Enter initial size of array: ");

    scanf("%d", &size);

 

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

    if (arr == NULL) {

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

        return 1;

    }

 

    // Step 2: Input initial elements

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

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

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

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

    }

 

    // Step 3: Display initial array

    printf("\nInitial Array Elements:\n");

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

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

    }

    printf("\n");

 

    // Step 4: Resize the array dynamically

    printf("\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 5: Input new elements if size increased

    if (newSize > size) {

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

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

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

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

        }

    }

 

    // Step 6: Display resized array

    printf("\nResized Array Elements:\n");

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

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

    }

    printf("\n");

 

    // Step 7: Free allocated memory

    free(arr);

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

 

    return 0;

}

Output

 
OUTPUT :
Enter initial size of array: 3
Enter 3 elements:
Element 1: 10
Element 2: 20
Element 3: 30

Initial Array Elements:
10 20 30

Enter new size of array: 5

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

Resized Array Elements:
10 20 30 40 50

Memory freed successfully.

Explanation

Step

Description

1

Allocate an array dynamically using malloc() based on initial size.

2

Accept and display initial elements.

3

Use realloc() to resize the array at runtime.

4

Add more elements if the new size is larger.

5

Display the resized array.

6

Release memory using free() to prevent memory leaks.