+ 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
3 Antworten
+ 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
+ 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.
0
I don’t know, but that’s a good question