#include <stdio.h>
#define LENGTH 3
char *words[LENGTH];
int main( int argc, char *argv[] )
{
char *pc; // a pointer to a character
char **ppc; // a pointer to a pointer character
printf( "\n------------Multiple indirection example\n" );
// initialize our array string
words[0] = "zero";
words[1] = "one";
words[2] = "two";
// print each element
for ( int i = 0; i < LENGTH; ++i )
{
printf( "%s \n", words[i] );
}
ppc = words; // initialize the pointer to pointer to a character
for( int i = 0; i < LENGTH; ++i) // loop over each string
{
ppc = words + i;
pc = *ppc;
while (*pc != 0) { // process each character in a string
printf("%c ", *pc); // print out each character of the string individually
pc += 1;
}
printf("\n");
}
return 0;
}
The part that says " char **ppc " declares a char double pointer. Then it says ppc = word . What is the difference between a regular pointer variable being assigned to words and this double pointer variable? I also don't get why a regular pointer variable would be assigned to have the value of a double pointer variable. Can someone explain this?
There are two things you need to learn:
All arrays naturally decay to pointers to their first element. So for example as an expression
wordis really the same as&word[0]. Sincewordis an array ofchar *elements, a pointer to such an element must then bechar **.For any pointer (or array)
pand indexi, the expressionp[i]is exactly the same as*(p + i). From this follows thatp[0]is the same as*(p + 0)which is the same as*p.If we now put it all together we start with
which according to point 1 above must the same as
It makes
ppcpoint to the first element of the arraywords.Then we have
which will then be equal to
I.e. it makes
ppcpoint to the i:th element in the arraywords.Finally we have
which is the same as
But since
ppcpoints to the i:th element of the arraywords, the last assignment is really the same asThe variable
ppcisn't really needed in this program, other than as an example.To illustrate it, lets "draw" it out...
We have the
wordsarray:In the first iteration of the loop, when
i == 0, then we havewhich leads to
+-----+ +---+ +--------+ | ppc | --> | 0 | --> | "zero" | +-----+ +---+ +--------+ | 1 | --> | "one" | +---+ +--------+ | 2 | --> | "two" | +---+ +--------+Then we have the second iteration, when
i == 1which then givewhich looks like
+---+ +--------+ | 0 | --> | "zero" | +-----+ +---+ +--------+ | ppc | --> | 1 | --> | "one" | +-----+ +---+ +--------+ | 2 | --> | "two" | +---+ +--------+And exactly the same for the third and last iteration of the loop.