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:

  1. Declare the pointer array.
  2. 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:

  1. Declare the pointer array:
  2. We declare the pointer array using the syntax int* array[ARRAY_SIZE];. This declares an array of ARRAY_SIZE elements, where each element is a pointer to an integer.

  3. Assign NULL to each element of the array:

  4. 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.
  5. Inside the loop, we assign NULL to each element using the assignment operator =.

  6. Print the array to verify the initialization:

  7. We use another loop to iterate over each element of the array and print its value.
  8. The format specifier %p is used to print the value of a pointer.
  9. The loop condition i < ARRAY_SIZE ensures that we iterate over all elements of the array.
  10. Inside the loop, we use printf to print the index i and the value of array[i].

By following these steps, you can initialize a pointer array with NULL in C.

[1]