Search code examples
cincrementdecrement

Pointer Increment and Decrement(*--*++p) in c


#include <stdio.h>

int main() {
 
    static char*s[]  = {"6642321","93456","134098","55513"};
    char ** str[] = {s+3,s+2,s+1,s};
    char ***p = str;
    **++p;
    printf("%s\n",*--*++p+2);
    return 0;
}

In this code on the printf statement *++p gives one address(s+1). In my understanding --(s+1) gives compilation error. But this code gives output as 42321. Why I am getting this answer. Please could anyone explain this code ?


Solution

  • In **++p;:

    • ++p increments p so it points to str+1 instead of its initial value, str.
    • The second * produces the element p points to (after the increment), and that is str[1].
    • The first * produces the element that str[1] points to, and that is *(s+2) or, equivalently, s[2].
    • Then this value is discarded, as the expression does nothing with it.

    In the *--*++p+2 in the printf:

    • ++p increments p so it points to str+2.
    • The second * produces the element p points to, and that is str[2].
    • The -- decrements str[2], so it changes from s+1 to s+0, or just s.
    • The first * produces the element str[2] points to (after the decrement), so it produces *s or, equivalently, s[0]. s[0] is a pointer to the first character of "6642321".
    • The +2 produces a pointer to two characters beyond this, so it points to the 4 character.

    Then this pointer to the 4 character is passed to printf. The characters starting at that point are 4, 2, 3, 2, 1, and a null character, so printf prints 42321.