So I have to find out why specific values are printed out, and I've solved most of it but, I've got a problem with the last three.
I'd be happy for any help
int main(void)
{
int myValues[] = { 9, 0, 12345, 1, 7, 2, 6, 3, 5, 4 };
mess(&myValues[3]); //starts function mess
}
void mess(int *n)
{
printf("mess :%d\n", *n++); //prints value of 3rd index (1) and sets pointer to fourth index
printf("mess: %d\n", *++n); //sets n to 5th index and prints its value
printf("mess: %d\n", -2[n]); //value: -3
printf("mess: %d\n", (-2)[n]); //value: 1
printf("mess: %d\n", n[-6]); //value: 32766
}
I just don't understand how the values -3, 1 and 32766 come to be
First, let's visualize the memory pointed to by n
, after the execution of first two printf()
statements:
int myValues[] = { 9, 0, 12345, 1, 7, 2, 6, 3, 5, 4 };
^
// n
Let's see one by one
Statement 1: printf("mess: %d\n", -2[n]); //value: -3
Check the operator precedence. -2[n]
is parsed as -(2[n])
. Thus, the -
is the sign, 2[n]
is the same as n[2]
which is the value 3
. Thus, the statement is the same as
printf("mess: %d\n", -(n[2]) );
Visualization:
int myValues[] = { 9, 0, 12345, 1, 7, 2, 6, 3, 5, 4 };
^ ^^
// n n+2
Statement 2: printf("mess: %d\n", (-2)[n]); //value: 1
Here, n[-2]
is the same as *(n-2)
. Result is the value at that index. (Check the above visualization).
Visualization:
int myValues[] = { 9, 0, 12345, 1, 7, 2, 6, 3, 5, 4 };
^ ^ ^
// n-2 n n+2
Finally, Statement 3: printf("mess: %d\n", n[-6]); //value: 32766
As per the current content of the pointer n
, the least accessible index is -5
, attempting to access the memory location at an index -6
is accessing out of bounds, causes undefined behavior. The result cannot be justified.
Visualization:
int myValues[] = { 9, 0, 12345, 1, 7, 2, 6, 3, 5, 4 };
??? ^ ^
// n-6 n-5 n
printf("mess: %d\n", -2[n]); //value: -3
-2[n]
is -(n[2])
(see here for an explanation on this quirk). At this point, n[2]
gets you 3
so -n[2]
is -3
.
printf("mess: %d\n", (-2)[n]); //value: 1
This is [-2]
, which means 2 to the "left" of where you started out, which result in 1
.
printf("mess: %d\n", n[-6]); //value: 32766
This goes to before the start of your array, and that's undefined behavior. It could do anything, but most likely it just prints some rubbish value by interpreting memory that it shouldn't access this way.
I'm not sure about how well defined the other statements of the code are. It's really bad practice, please don't write code like this. As you aptly put, it's a mess
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With