Simple test program on pointers in C

This post only documents a simple program to show the effects of * and & in C and does not attempt to explain what pointers are.
For a quick read, check out The 5-Minute Guide to C Pointers.

Program:

#include <stdio.h>

int main()
{
    // lval (left-hand side value - write) = rval (right-hand side value - read)
    int i = 5;
    int *j = &i;
    int **k = &j;

    printf( // *i invalid - error: indirection requires pointer operand ('int' invalid)
        "\n i=%d\n &i=%p\n *&i=%d\n &*&i=%p\n",
            i,     &i,     *&i,     &*&i
    );
    printf(
        "\n j=%p\n &j=%p\n *j=%d\n *&j=%p\n &*j=%p\n *&*j=%d\n &*&j=%p\n",
            j,     &j,     *j,     *&j,     &*j,     *&*j,     &*&j
    );
    printf( // &&k invalid - error: use of undeclared 'k'
        "\n k=%p\n &k=%p\n *k=%p\n *&k=%p\n &*k=%p\n &*&k=%p\n *&*k=%p\n **k=%d\n &**k=%p\n **&k=%p\n &**&k=%p\n",
            k,     &k,     *k,     *&k,     &*k,     &*&k,     *&*k,     **k,     &**k,     **&k,     &**&k
    );
    printf("\n");

    return 0;
}

To run:

  • Save the program as test.c.
  • In the terminal, run gcc -o runtest test.c to compile it. The -o specifies the name of the output file. On Mac machines, Clang replaces GCC.
  • Type ./runtest to run the compiled executable.
  • Just for fun: To generate the equivalent x86 assembly language for the program (GAS syntax), type gcc -S test.c in the terminal, which will generate test.s. To ignore warnings during compilation, e.g. for the purposes of security testing, run GCC with the -w option.

Sample Output:


 i=5
 &i=0x7fff50883bc8
 *&i=5
 &*&i=0x7fff50883bc8

 j=0x7fff50883bc8
 &j=0x7fff50883bc0
 *j=5
 *&j=0x7fff50883bc8
 &*j=0x7fff50883bc8
 *&*j=5
 &*&j=0x7fff50883bc0

 k=0x7fff50883bc0
 &k=0x7fff50883bb8
 *k=0x7fff50883bc8
 *&k=0x7fff50883bc0
 &*k=0x7fff50883bc0
 &*&k=0x7fff50883bb8
 *&*k=0x7fff50883bc8
 **k=5
 &**k=0x7fff50883bc8
 **&k=0x7fff50883bc8
 &**&k=0x7fff50883bc0