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 ie '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:
mbb
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
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 ie m
++*b;
==> here you are incrementing the value contained in b, ie a
, hence after increment it becomes b
*c ==> pointing to incremented value of previous operation ie b
Let's consider the precedence and associativity of prefix
, postfix
, and *
dereferencing operator.
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.
Associativity : Right to left for prefix
and * dereference operator
.
Initially, a
, b
, c
store the address of the first element of the array.
*++a
can be expressed as *(++a)
, since associativity is right to left. (Note: prefix
and * dereference operator
have same precedence).
Hence, *(++a)
= *(a+1)
= m
Similarily, ++*b
can be expressed as ++(*b)
= ++(a)
= b
(since *b = a
)
Since, the value at the first address of the array has been changed, *c
= b
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.