Horje
How to Initialize Array of Pointers in C?

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)




Reffered: https://www.geeksforgeeks.org


C Language

Related
C Program to Find Minimum Value in Array C Program to Find Minimum Value in Array
How to Use typedef for a Union in C? How to Use typedef for a Union in C?
How to use typedef for a Struct in C? How to use typedef for a Struct in C?
How to Access Array of Structure in C? How to Access Array of Structure in C?
How to Sort an Array of Structs Based on a Member in C? How to Sort an Array of Structs Based on a Member in C?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13