質問

Could someone explain this little code snippet for me?

Given:

int a[3] = {2,3,4};

Why does the following evaluate to true?

static_cast<void *>(a) == static_cast<void *>(&a); // Why is this true?

Is this saying that the address of a is the same as a? If so, why is this true?

役に立ちましたか?

解決

It is because address of the variable a concides with the address of the first element of array a. You can also think of a is &a[0] which is clearer when we say "the address of the first element of the array").

Another example,

struct X
{
    int i;
};

X x;

Here also the address of variable x concides with the address of x.i (which is the first element of the aggregate), so this would print 1:

std::cout << (&x == &(x.i)) << std::endl; //1

So in your case, &a is like &x, and a (or &a[0]) is like &(x.i).

Note that in C++ a and x are both called aggregate (see my answer here: What is an aggregate?)

他のヒント

In almost all contexts, the name of an array decays into a pointer to the first element of the array. So in static_cast<void*>(a), the a decays into &a[0]; it's type is "pointer to int". The expression evaluates to the address of the first element of the array. In static_cast<void*>(&a), however, &a is the address of the array itself; its type is "pointer to array of 3 int". That's why the casts are needed here: the two expressions without the casts would have different types, and could not be compared. Both can be converted to void* and compared. So what this code is illustrating is that the address of the first element of an array is the same as the address of the array, i.e., there's no padding at the front.

The name of an array usually evaluates to the address of the first element of the array, so array and &array have exact the same value.

However, they are different types. For the following array:

int a[8];

a+1 is the address of the array a + sizeof(int) but &a+1 will be the address of the array a + 8 * sizeof(int).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top