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.


#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
        "\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

    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: