how to initiate pointer array with NULL in c
Initializing a Pointer Array with NULL in C
To initialize a pointer array with NULL in C, you can follow these steps:
- Declare the pointer array.
- Assign NULL to each element of the array.
Here's an example code snippet that demonstrates how to initialize a pointer array with NULL:
#include <stdio.h>
#define ARRAY_SIZE 5
int main() {
int* array[ARRAY_SIZE]; // Declare the pointer array
int i;
for (i = 0; i < ARRAY_SIZE; i++) {
array[i] = NULL; // Assign NULL to each element of the array
}
// Print the array to verify the initialization
for (i = 0; i < ARRAY_SIZE; i++) {
printf("array[%d] = %p\n", i, array[i]);
}
return 0;
}
In this example, we declare a pointer array array
with a size of ARRAY_SIZE
. We then use a loop to assign NULL to each element of the array. Finally, we print the array to verify that each element is initialized with NULL.
Explanation of each step:
- Declare the pointer array:
We declare the pointer array using the syntax
int* array[ARRAY_SIZE];
. This declares an array ofARRAY_SIZE
elements, where each element is a pointer to an integer.Assign NULL to each element of the array:
- We use a loop to iterate over each element of the array and assign NULL to it. The loop condition
i < ARRAY_SIZE
ensures that we iterate over all elements of the array. Inside the loop, we assign NULL to each element using the assignment operator
=
.Print the array to verify the initialization:
- We use another loop to iterate over each element of the array and print its value.
- The format specifier
%p
is used to print the value of a pointer. - The loop condition
i < ARRAY_SIZE
ensures that we iterate over all elements of the array. - Inside the loop, we use
printf
to print the indexi
and the value ofarray[i]
.
By following these steps, you can initialize a pointer array with NULL in C.