About Blog Contact

Pointer Stew!

I saw this puzzle somewhere on Stack Overflow. So I went through each step and wrote some comments:

#include<stdio.h>
 
char* c[] = { "ENTER", "NEW", "POINT", "FIRST" }; // An array of pointer-to-chars. c[1] is the char* to NEW, c[1][1] = 'E'
char** cp[] = { c+3, c+2, c+1, c }; // An array of pointer-to-(pointer-to-chars). cp[1] is the address of "P" in "POINT" 
char*** cpp = cp; // the pointer to c

int main(int argc, char** argv) {
    printf("%s", **++cpp);
    // *(*(++cpp))
    // ++cpp : pointer to c+2, type char***
    // *(++cpp): pointer that points to the starting address of "POINT", type char**
    // *(*(++cpp)) : starting address of "POINT", type char*
    printf("%s ", *--*++cpp+3);
    // *(--(*(++cpp)))+3
    // ++cpp: pointer to c+1, type char***
    // *(++cpp) : pointer to the starting address of "NEW", type char**
    // --*(++cpp) : pointer to starting address of "ENTER", type char**
    // *(--*(++cpp)) : starting address of "ENTER", type char*
    // *(--*(++cpp)) + 3 : starting address of "ER" in "ENTER", type char*
    printf("%s", *cpp[-2]+3);
    // cpp[-2] : note now cpp is already cpp_0+2, so cpp[-2] is c+3
    // *(cpp[-2]) : starting address of c+3, that is "FIRST"
    // *(cpp[-2]) + 3 : address of "S", so when printed, the outcome is "ST"
    printf("%s\n", cpp[-1][-1]+1);
    // cpp[-1] is cpp_0 + 2 - 1 = cpp_0 + 1, that is c+2
    // cpp[-1][-1]:  pointer to c[1], that is "NEW"
    // cpp[-1][-1] + 1: pointer to "E" in "NEW". prints "EW"
    return 0;

    // Same as printf("POINTER STEW\n");
}

I think that after going through this code, you definitely would know your pointers.

Another source for this puzzle can be found here