I’m new to c++, I have a question about pointer and array
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
int a[5] = {1,7,-1,0,2};
int b[5] = {7,5,3,4,2};
int c[5] = {1,4,5,3,1};
*(&a[2] + (&c[5] - 7 - &c[0]))= a[1];
*(&a[3] + (&c[5] - 7 - &c[0]))= b[1];
*(&a[4] + (&c[5] - 7 - &c[0]))= c[1];
int x = a[0] - a[1] + a[2] - a[3];
printf ("%d", x);
return 0;
}
Why is that x = 6? thx
Beginning with:
First we notice the subexpression
(&c[5] - 7 - &c[0])is used multiple times.(&c[5] - 7 - &c[0])can be rearranged as(&c[5]- &c[0] - 7 ), which is the address of the fifth int ofc, minus the address of the 0th int ofc, which results in5*, so the expression is(5-7)or-2.(&a[2] -2)is the address of the second index minus two, which is the same as&a[0]. So*(&a[2] + (&c[5] - 7 - &c[0]))isa[0].By extrapolation, the rest of the code is as follows:
So then we get to the final equation:
and when we find the values in those positions of the array:
Which results in
6.*the addresses are not actually 5 apart (they’re usually 20 or 40), but when you do subtraction of
intpointers, it results in the number ofints between them, which is five.