What is the relationship between an array and its address?

  • A+
Category:Languages

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).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: