Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, How many addresses do arrays have?

Tags:

c++

arrays

Does the array in c++ have address for each element? Or the array has just one address?

like image 452
Billy Milligan Avatar asked Dec 04 '25 04:12

Billy Milligan


2 Answers

Given an array like:

int a[4];

each of the 4 int in a has its own address (separated by the size of an int on your platform).

The address of a is simply the address of the first int in the array. So you can think of an array as having just one address, that is also the address of the first element. But all the elements of the array have their own address which can be used to refer to the elements. In fact, you can even access the individual bytes of each element, but you should be careful when interpreting what those bytes mean, depending on the data type of the elements.

like image 125
cigien Avatar answered Dec 06 '25 21:12

cigien


Each element of an array has own address. Address of an array is the address of it's first element.

int main(int, char**)
{
    int n[10];
    if (std::begin(n) == &n[0]) {
        std::cout << "equal";
    }
    else {
        std::cout << "not equal";
    }
    return 0;
}

Output:
equal
like image 21
Amir Kadyrov Avatar answered Dec 06 '25 20:12

Amir Kadyrov