Answer P21

value = 32
*pv   = 32
*(*ppv) = 32

#include  <stdio.h> 

void main ( void )
{
  int value;
  int *pv;
  int **ppv;

  value = 32;
  pv = &value;
  ppv = &pv;

  printf("value = %d\n", value );
  printf("*pv   = %d\n", *pv );
  printf("*(*ppv) = %d\n", *(*ppv) );
  
  system("pause");
}

 

There are three variables in this program: value, pv, and ppv. Each is implemented as several bytes in main memory (usually 4 bytes), and each has an address.


Review: The following

  value = 32;

puts the value 32 into the bytes that implement the variable value, and so the following

    printf("value = %d\n", value );

goes to that variable, gets the value held in it, and prints it out. The following

  pv = &value;

gets the address of value and puts it into the variable pv. (This is shown as the top arrow in the picture.) Now the following

  printf("*pv   = %d\n", *pv );

gets the address in pv and follows it to find the place in memory where an integer is stored, gets that integer and prints it out.

New Stuff: The following

   ppv = &pv;

puts the address of pv into the variable ppv. (This is shown as the bottom arrow in the picture.) This is perfectly OK. The variable pv is implemented (usually) as four bytes, just as the other variables, and certainly has an address. That address (that pointer value) is asked for by &pv. The following

   *ppv 

means follow the pointer in ppv to a place in memory and get the value stored there. This is the value in pv, which itself happens to be a pointer value. Now the outer star in *( *ppv ) means to follow the pointer we just got. This leads to value. So

  printf("*(*ppv) = %d\n", *(*ppv) );

follows the pointer in ppv to pv, then follows the pointer in pv to value and gets the integer stored there.

Programmers sometimes speak each * as a "hop." (Like a rabbit.) So *( *ppv ) means "hop hop" to an int.



Back to Puzzle Home