Broad Network


Array of Pointers in the C Computer Language

Part 18 of Complete C Course

Foreword: Array of Pointers in the C Computer Language

By: Chrysanthus Date Published: 4 Jun 2024

Introduction

An array of strings is an array of constant pointers (see the previous tutorial for array of strings - constant pointers). That is not the only possibility. It is possible to have an array of pointers to integers or an array of pointers to floats, or an array of pointers to chars, etc. The pointers do not necessarily have to be constant pointers. Each pointer points to the first byte of the object. An integer for example occupies four bytes; the pointer points to the first byte. The following program shows an array of integer constant pointers:

    #include <stdio.h>
    
    int int0 = 0; int int1 = 10; int int2 = 100; int int3 = 1000; int int4 = 10000;
    int * const ptrInt0 = &int0; int * const ptrInt1 = &int1; int * const ptrInt2 = &int2;
    int * const ptrInt3 = &int3; int * const ptrInt4 = &int4;
    
    int *arr[] = {ptrInt0, ptrInt1, ptrInt2, ptrInt3, ptrInt3};

    int main(int argc, char *argv[])
    {
        printf("%i, ", *ptrInt0); printf("%i, ", *ptrInt1); printf("%i, ", *ptrInt2);
        printf("%i, ", *ptrInt3); printf("%i\n", *ptrInt4);

        return 0;
    }

The output is: 0, 10, 100, 1000, 10000 . Note how the array was declared. The pointer to the array is constant and cannot be incremented or decremented. The pointer to the first byte of each object is constant, and also cannot be incremented or decremented.

Can the Array have Pointers to Different Types? - No
When declaring the array, as in "int *arr[]" , all the objects the pointers point to, must be of the same type. In this case, all the objects the pointers in the array point to, are of type, int. The declaration of an array of char pointers, will begin with "float *arr[]". The declaration of an array of float pointers, will begin with "float *arr[]"; and so on.

Thanks for reading. See you in the next tutorial.




Related Links

More Related Links

Cousins

BACK NEXT

Comments