Reputation: 59
#include<stdio.h>
int main() {
int buff[] = {1,2,3,4,5,6,9,10};
char c = (buff+1)[5];
printf("%d\n",c);//output is 9
return 0;
}
Can someone explain it clearly how this is happening and why
Upvotes: 2
Views: 109
Reputation: 3751
Recall:
In C the square braces [ ]
are implicitly *( ... )
.
What is going on in the snippet of code you provided is not obvious pointer arithmetic. This line:
char c = (buff+1)[5];
... is equivalent to the following (by the C standard):
char c = *( ( buff + 1 ) + 5 );
... which points to the 7th element in the array (6th position) and dereferences it. It should output 9, not 19.
Remark:
Following the note about square braces, it's important to see that the following is equivalent.
arr[ n ] <=> n[ arr ]
... where arr
is an array and n
is a numerical value. A more complicated example:
' '[ "]; i < 0; i++; while ( 1 ); do something awesome (y)." ];
... of entirely valid pointer arithmetic.
Upvotes: 8
Reputation: 47784
{1, 2, 3, 4, 5, 6, 9, 10};
| |
buff buff+1 = {2, 3, 4, 5, 6, 9, 10} (say buff_1)
|
buff_1[5] = 9
Upvotes: 6