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

99 views Asked by At
#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 ?

2

There are 2 answers

0
Eric Postpischil On BEST ANSWER

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.

0
dbush On

The result of the unary indirection operator * is always an lvalue. This means it refers to a object that can be assigned to.

In this case subexpression ++p in the printf is a pointer pointing to str[2]. So *++p gives you the object str[2] which has the value s+1.

This means that --*++p is equivalent to --str[2], which in turn sets its value to s+0 (i.e. s after pointer decay). Dereferencing that as *--*++p+2 gives you the object s[0]. Then 2 is added to the value stored there i.e. a pointer to the start of the string "6642321", resulting in a pointer to the third character of that string. That pointer is passed to printf which in turn prints 42321.