Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between an array and its address?

Tags:

c++

arrays

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?

like image 305
user10906383 Avatar asked Feb 22 '19 19:02

user10906383


2 Answers

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

like image 57
P.P Avatar answered Oct 18 '22 21:10

P.P


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.

like image 20
SergeyA Avatar answered Oct 18 '22 21:10

SergeyA