Open In App

How to Initialize Array of Pointers in C?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Arrays are collections of similar data elements that are stored in contiguous memory locations. On the other hand, pointers are variables that store the memory address of another variable. In this article, we will learn how to initialize an array of pointers in C.

Initialize Array of Pointers in C

We can simply initialize an array of pointers by assigning them some valid address using the assignment operator. Generally, we initialize the pointers that currently do not point to any location to a NULL value. This helps us avoid bugs such as segmentation faults.

C Program to Initialize an Array of Pointers

C




// C  program to initialize array of pointers
#include <stdio.h>
  
int main()
{
    // declare an array of pointers to store address of
    // elements in array
    int* ptr[4];
  
    // initializing the pointers to the NULL
    for (int i = 0; i < 4; i++) {
        ptr[i] = NULL;
    }
    // Print the elements and the address of elements stored
    // in array of pointers
    for (int i = 0; i < 4; i++) {
        if (ptr[i])
            printf("ptr[%d] = %d\n", i, *ptr[i]);
        else
            printf("ptr[%d] = NULL\n", i);
    }
    
    return 0;
}


Output

ptr[0] = NULL
ptr[1] = NULL
ptr[2] = NULL
ptr[3] = NULL

Time Complexity: O(N) where N is the number of elements in the array of pointers.
Auxiliary Space: O(N)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads