Nice Question.
Let's get few things first.
&arr and arr have same values. This statement is correct, but in addition to this &arr points to whole array and arr points to first element of the array, what I mean to say is that even though value of &arr and arr is same if you do (&arr+1) it will skip through the whole array and point to (not access to) next memory location after the array whereas if you do (arr+1) it will point to next element in the array. Get your head around this first. Read more here.
https://arjunsreedharan.org/post/69303442896/the-difference-between-arr-and-arr-how-to-find
No. of elements in the array is 210.
First Statement is printf(
"%d\n"
, (&arr + 1) - &arr);
This is a normal pointer arithmetic, which is (address-address)/sizeof(object).
So, here the object is whole [5][6][7] array and contains 210 elements.
If array starts with address 100 then (&arr+1) is 310 and according to formula (310-100)/210=1, which is correct.
The second statement is printf
(
"%d\n"
, (
char
*)(&arr + 1) - (
char
*)&arr);
See, till now I'm not sure about it but I think I'm correct about what (char *)(&arr +1 ) is doing, what I'm able to understand is that it is a simple subtraction of two number but both contain inside a pointer which is of char type which should be generated by the compiler itself, temporarily. (THE PREVIOUS LINE IS MY ASSUMPTION OF HOW COMPILER IS Working HERE based on the previous observation of when we pass an expression as a parameter to a method compiler first solve that expression and make it allocate in a temporary memory and then pass the value
int main(){
int a=10,b=20;
int c=add(a+10,b);
printf("sum is %d\n",c);
return 0;
}
int add(int a, int b){
return a+b;
}
Output is :sum is 40
here compiler allocate a temporary memory to a+10 and then pass the value 20 to add.
Coming back to printf
(
"%d\n"
, (
char
*)(&arr + 1) - (
char
*)&arr);
This says &arr+1=310(address)--> then (char*)(310) = put 310 inside a char pointer generated by the compiler.
Similarly, for (char *)(&arr)-->(char *)(100), and now simple pointer subtraction of "values" in those pointer will happen i.e. (310-100)/1=210.(Ask yourself why divide by 1? If not able to get it, read more about pointer arithmetic.) (A small example is this https://ideone.com/NfZ8nJ).
Now, the Similar concept applies to the third statement printf
(
"%d\n"
, (unsigned)(arr + 1) - (unsigned)arr);
Where (arr + 1) is type-casted into a unsigned number(signed means both -ve and +ve, unsigned means only +ve values read more on Wikipedia), but the point to be noted that here arr pointing to "First element of the array"(read the first passage written carefully) and (arr+1) give me address of 42 elements ahead of from wherever I am right now (Why?). So (unsigned)(arr + 1) - (unsigned)arr = 142-100=42.
Now, I think you can figure out how the Fourth statement is working.
Ask in comment, if you didn't get something in answer.