C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Allocate array using malloc() function

C Program: Allocate array using malloc() function

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    int *arr;

    int n, i;

 

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Allocate memory dynamically using malloc()

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

 

    // Check if memory allocation was successful

    if (arr == NULL) {

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

        return 1;

    }

 

    // Input elements

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

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

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

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

    }

 

    // Display elements

    printf("\nArray elements are:\n");

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

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

    }

 

    // Free allocated memory

    free(arr);

 

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

 

    return 0;

}

Output

 
OUTPUT 1 :

Enter number of elements: 5

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

Array elements are:
10 20 30 40 50 

Memory has been freed successfully.

Explanation

Concept

Description

malloc()

Allocates memory dynamically at runtime. Returns a pointer to the allocated block.

sizeof(int)

Ensures enough memory is allocated for each integer element.

if (arr == NULL)

Checks whether memory allocation failed.

free(arr)

Releases the dynamically allocated memory to avoid memory leaks.