The following code:
#include<iostream>
int main (void) {
int lista[5] = {0,1,2,3,4};
std::cout << lista << std::endl;
std::cout << &lista << std::endl;
std::cout << lista+1 << std::endl;
std::cout << &lista+1 << std::endl;
std::cout << lista+2 << std::endl;
std::cout << &lista+2 << std::endl;
std::cout << lista+3 << std::endl;
std::cout << &lista+3 << std::endl;
return (0);
}
Outputs:
0x22ff20
0x22ff20
0x22ff24
0x22ff34
0x22ff28
0x22ff48
0x22ff2c
0x22ff5c
I understood that an array is another form to express a pointer, but we cannot change its address to point anywhere else after declaration. I also understood that an array has its value as the first position in memory. Therefore, 0x22ff20
in this example is the location of the array's starting position and the first variable is stored there.
What I did not understand is: why the other variables are not stored in sequence with the array address? I mean, why lista+1
is different from &lista+1
. Should not they be the same?
In pointer arithmetic, types matter.
It's true that the value is the same for both lista
and &lista
, their types are different: lista
(in the expression used in cout call) has type int*
whereas &lista
has type int (*)[5]
.
So when you add 1 to lista
, it points to the "next" int
. But &lista + 1
points to the location after 5 int's (which may not be a valid).
Answering the question as asked:
std::cout << &lista+1 << std::endl;
In this code you take the address of array lista
and add 1
to obtained answer. Given the sizeof of the array is sizeof(int) * 5
, which means when you increment a pointer to it by 1 you add sizeof(int) * 5
to the pointer address, you end up with a number you see.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With