1

Here in the below program, the 'c' pointer has not been modified. Still, it's printing the second element of the array instead of the first one i.e. 'a'. Can anyone explain this behavior? The first two characters are printed correctly but the third one is something unusual.

#include <stdio.h>
int main()
{
    char arr[] = {'a','m','r'};
    char *a = arr;
    char *b = arr;
    char *c = arr;
    
    *++a;
    ++*b;
    
    printf("%c %c %c",*a,*b,*c);

    return 0;
}

Output:

m b b

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
Jay
  • 43
  • 6

3 Answers3

2
char arr[] = {'a','m','r'};
              /|\
             a b c

after *++a;

char arr[] = {'a','m','r'};
              /\   |
             b c   a

after ++*b;

char arr[] = {'b','m','r'};
              /\   |
             b c   a
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
1

Initially a, b and c all pointing to first element of the array.

*++a; ==> the operation increments address so it will point to next location and deference the value in it, hence it will point to next location i.e m

++*b; ==> here you are incrementing the value contained in b, i.e a, hence after increment it becomes b

*c ==> pointing to incremented value of previous operation i.e b

csavvy
  • 761
  • 4
  • 13
0

Let's consider the precedence and associativity of prefix, postfix, and * dereferencing operator.

  1. Precedence : Postfix has higher precedence than * dereference operator and prefix operator. But prefix and * dereference operator have same precedence. We have to consider the associativity of same precedence operators.

  2. Associativity : Right to left for prefix and * dereference operator.

  3. Initially, a, b, c store the address of the first element of the array.

  4. *++a can be expressed as *(++a), since associativity is right to left. (Note: prefix and * dereference operator have same precedence).

  5. Hence, *(++a) = *(a+1) = m

  6. Similarily, ++*b can be expressed as ++(*b) = ++(a) = b (since *b = a)

  7. Since, the value at the first address of the array has been changed, *c = b.

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26