c - Why "*(&arr+4)" is different then "&arr[4]"? -


int arr[] = { 0, 1, 2, 3, 4, 5 }; 

i performing address operation tests, increase understanding of ref , deref. here lot of confusion.

i found out &*(arr+4) uses same address &arr[4]but never met such assignment &*

also figured *(&arr+4) uses same address &arr+4 doesn't make sense me.

i couldn't find info that, ask here, why *(&arr+4) uses same address &arr+4 , why *(&arr+4) different &arr[4]?

arr array:

arr: int[6] [0|1|2|3|4|5] 

when used in expression other sizeof arr or &arr, array decays pointer first element of array:

(arr+0): int * [*]  |  v [0|1|2|3|4|5] 

when integral value added pointer, pointer address (sizeof (t)) * n bytes later in memory (where t type pointed pointer, , n integral value added pointer):

(arr+4): int *         [*]          |          v [0|1|2|3|4|5] 

when pointer dereferenced, value pointed to:

*(arr+4): int           4 /* specifically, 4 in fifth position in `arr` */ [0|1|2|3|[4]|5] 

when address taken of int, pointer points int:

&*(arr+4): int *         [*] /* notice, same (arr+4) */          |          v [0|1|2|3|4|5] 

array indexing equivalent pointer-addition followed dereferencing:

arr[4] == *(arr+4) /* see above definition of *(arr+4) */ 

so yes... &*(arr+4) , &arr[4] equivalent.

when address of array taken, pointer array:

&arr: int (*)[6] [*] /* points array whole, not first element of array */  |  v  [0|1|2|3|4|5] 

when increment pointer, same rules apply above:

                                    &arr + 4: int(*)[6]                /*points memory that*/    [*]                /* isn't part of array... */     |                /*  undefined behaviour       */     v [0|1|2|3|4|5][x|x|x|x|x|x][x|x|x|x|x|x][x|x|x|x|x|x][x|x|x|x|x|x] 

since has undefined behaviour, can't reason without reference underlying machine architecture , compiler implementation.

if imagine defined (as case if arr part of larger array)... can continue. dereferencing pointer array gives array again:

             /*the 5th array in array of arrays*/ *(&arr+4): int[6]    [0|1|2|3|4|5][x|x|x|x|x|x][x|x|x|x|x|x][x|x|x|x|x|x][[x|x|x|x|x|x]] 

you find *(&arr+4) , (&arr+4) have same address, since *(&arr+4) decays pointer first element of *(&arr+4), , array starts @ first element, pointer start of array , pointer first element of array identical.

*(&arr+4) different &arr[4] since refers different thing (see above).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -