About arrays | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

About arrays

I noticed that if you declare a pointer P equal to (*(&Array + 1) - 1) P points to the last element of Array. Can someone exaplain me how?

6th Feb 2019, 9:41 PM
OrHy3
OrHy3 - avatar
2 Antworten
+ 2
&array returns the address of the array, a pointer to a pointer, T**. T(*)[size] actually but lets not overcomplicate that. Where T is the type. Adding a value to an address is equivalent to doing address + size_of_object * added_value. It's just that the compiler does the sizeof automatically, just imagine doing that yourself in assembly. :( If an array stores 6 integers and is located at 0x22fe30, assuming an int is 4 bytes, the entire size of the array becomes 6 * 4 = 24, then the formula becomes 0x22fe30 + 24 * 1 = 0x22fe48 which points 1 past the array. Then you do *0x22fe48 - 1 which takes the pointed-to type, which is another pointer, int*. Taking the size of that pointed-to type would be 4 so 0x22fe48 - 4 * 1 = 0x22fe44 which points to the last element of the array. Notice that this only works if the array is in the same scope as it was created, if you use an array that was passed to a function it would decay to a normal pointer, its size information would be lost and then this wouldn't work anymore.
6th Feb 2019, 10:26 PM
Dennis
Dennis - avatar
0
I understood, thanks for the help.
6th Feb 2019, 10:51 PM
OrHy3
OrHy3 - avatar