+ 1

Weird C pointer assignment

I saw code similar to this in a challenge and it doesn’t make sense to me, could someone please explain it? https://code.sololearn.com/cut9P4e9EJQL/?ref=app

16th Dec 2022, 11:46 PM
Edward Finkelstein
Edward Finkelstein - avatar
3 Respostas
+ 7
"&arr" is of type <int (*)[3]> "a pointer to an array of 3 ints". pointer arithmetic says adding an integer N to a pointer to an element of an array with index K produces a pointer to an element of the same array, with index K+N since “&arr” is pointer to array of 3 ints, addition of 1 resulted in an address with increment of (assuming sizeof int is 4 bytes) 4 x 3 = 12 (we end up to the addr of the next array of 3 ints if there was one ) which is decayed to int* (a pointer to an integer), subtraction of 1 resulted in an address with decrement of 4. +-----+-----+-----+-----+-----+-----+ | 1 | 2 | 3 | | | +-----+-----+-----+-----+-----+-----+ ^ ^ ^ ^ | | | | | | | | | | | | &arr | ptr-1 &arr + 1 == ptr | | | | arr arr + 1
17th Dec 2022, 12:24 AM
MO ELomari
MO ELomari - avatar
+ 2
The expression &arr+1 computes the address of one past the end of the array arr. This is equivalent to &arr[3]. The (int*) typecast converts the address to a pointer of type int*. The expression p-1 subtracts 1 from the pointer p, resulting in the address of the last element in the array arr, which is &arr[2]. The * operator dereferences the pointer, resulting in the value of the last element in the array, which is 3.
17th Dec 2022, 4:31 PM
Calviղ
Calviղ - avatar
0
I don’t know, but that’s a good question
16th Dec 2022, 11:53 PM
Owen Holmes
Owen Holmes - avatar