C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Allocate array using calloc() function

C Program: Allocate array using calloc() 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 calloc()

    arr = (int*) calloc(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

calloc(n, sizeof(int))

Allocates memory for n elements, each of size int, and initializes all bytes to zero.

malloc() vs calloc()

malloc() leaves memory uninitialized, while calloc() initializes it to zero.

free(arr)

Releases the allocated memory once it’s no longer needed.

if (arr == NULL)

Checks if allocation failed (returns NULL if insufficient memory).