Please explain the associativity of the operators in this code
-
04-07-2021 - |
Pergunta
#include <stdio.h>
int main(void)
{
char s[] = {'a','b','c','\n','c','\0'};
char *p;
p=&s[3];
printf("%d\t",++*p++);
printf("%d",*p);
return 0;
}
output: 11 99
Please explain the output. Why there is an increment in the address?
Solução
The only thing I see that could possibly be confusing is
++*p++
Postincrement has higher precedence than the dereference operator, so fully parenthesized it looks like
++(*(p++))
Which postincrements p
, dereferences the original value of p
to get a char
, then preincrements the value of the char
, and then the new value gets printed by printf
as an integer.
So both p
and what p
is pointing at get incremented.
Outras dicas
pointers in C are just integers which represent a memory location. Arrays in C are always in continuous memory blocks. So when you have a pointer which points to the third element of an array, and you add 1 from the pointer, it points at the fourth element.
In case you are confused about ++*p++
: That's because of the different between pre-increment (++p)
and post-increment (p++)
. There is an easy moniker for that for people who hate C++:
"C++ - change the language, return the old problems".
You should look at the operator precedences.
The expression ++*p++
is evaluated as((*p) + 1)
by the compiler, and it also have a side-effect: it increments the value of *p
and p
. With a ASCII-compatible charset, this instruction prints 11
('\n'+1 == 10+1 == 11
) on the standard output. The second printf
call prints the value of s[4]
('c'
).