Open In App

How to Initialize a Dynamic Array in C?

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, dynamic memory allocation is done to allocate memory during runtime. This is particularly useful when the size of an array is not known at compile time and needs to be specified during runtime. In this article, we will learn how to initialize a dynamic array in C.

Initializing a Dynamic Arrays in C

Dynamic Arrays in C, can be initialized at the time of their declaration by using the malloc() function that allocates a block of memory and returns a pointer to it, or calloc() function that allocates memory for the given size and initializes all bytes to zero. After allocation, we can initialize the elements of the array using the for loop.

C Program to Dynamically Initialize an Array

The below example demonstrates the use of the malloc function to initialize a dynamic array in C.

C
// C program to demonstrate how to dynamically allocate
// and initialize an array

#include <stdio.h>
#include <stdlib.h>

int main()
{
    // Take array size as input from user
    printf("Enter the size of the array: ");
    int size;
    scanf("%d", &size);

    // Dynamically allocate an array
    int* arr = (int*)malloc(size * sizeof(int));

    // Check if the memory has been successfully allocated
    if (arr == NULL) {
        printf("Memory not allocated.\n");
        return 1; // Exit the program
    }

    // Initialize values to the array elements
    for (int i = 0; i < size; i++) {
        arr[i] = i + 1;
    }

    // Print the array elements
    printf("Elements of the array are: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Deallocate the memory
    free(arr);

    return 0;
}


Output

Enter the size of the array: 5
Elements of the array are: 1 2 3 4 5

Time Complexity: O(n), where n is the size of the dynamically allocated array.
Auxiliary Space: O(n)

Note: Always remember to deallocate the memory using the free() function after use to prevent memory leaks.


Next Article

Similar Reads