C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Input & print dynamic array

C Program: Input & print dynamic array

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int *arr;

    int n, i;

 

    // Step 1: Get array size from user

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Step 2: Dynamically allocate memory using malloc

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

 

    if (arr == NULL) {

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

        return 1;

    }

 

    // Step 3: Input array elements

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

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

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

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

    }

 

    // Step 4: Print the array elements

    printf("\nYou entered:\n");

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

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

    }

 

    // Step 5: Free allocated memory

    free(arr);

 

    return 0;

}

Output

 
OUTPUT :
Enter number of elements: 5
Enter 5 elements:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

You entered:
10 20 30 40 50

Explanation

Step

Description

malloc()

Allocates memory dynamically at runtime.

arr[i]

Accesses and stores user inputs in the allocated memory.

free()

Deallocates the memory to avoid memory leaks.