C - Dereference array of pointers

Introduction

Consider the following code.

Demo

#include <stdio.h>

int main()/*w w w  .  j a  va 2s . c  om*/
{
    char *fruit[] = {
        "watermelon",
        "banana",
        "pear",
        "apple",
        "coconut",
        "grape",
        "blueberry"
    };
    int x;

    for(x=0;x<7;x++)
    {
        putchar(**(fruit+x));
        putchar('\n');
    }

    return(0);
}

Result

To understand the **(fruit+x) construct, work from the inside out:

fruit+x 

Variable fruit contains a memory address. It's a pointer!

The x is a value incrementing by one unit.

In this case, the unit is an address because all elements of the fruit array are pointers.

*(fruit+x) 

It's the contents of the address fruit+x.

From the code, fruit is an array of pointers. So the result of the preceding operation is a pointer!

** operator is almost always tied to an array of pointers; or, an array of strings.

Related Topic