How to Initialize Array of Pointers in C?
Last Updated :
22 Feb, 2024
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
#include <stdio.h>
int main()
{
int * ptr[4];
for ( int i = 0; i < 4; i++) {
ptr[i] = NULL;
}
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)
Share your thoughts in the comments
Please Login to comment...