Home > Enterprise >  C 11 about *begin(a)
C 11 about *begin(a)

Time:12-12

#include<iterator>
#include<iostream>
int a[5][4];
int main()
{
    cout << *begin(a);
}

Why this cout will print the same as begin(a).
It seems the * does not dereferencing the pointer return by begin(a) ?
Can anyone tell me why?

CodePudding user response:

Here * affects only the type of the pointer, and not its numerical value.

std::begin(a) returns a pointer to the first element of a, of type int (*)[4] (pointer to an array of 4 ints).

*std::begin(a) returns int[4]. Since cout can't print arrays directly, the array then decays to the pointer to its first element, of type int *, and is printed as such.

**std::begin(a) would return an int.

CodePudding user response:

You have a two-dimensional array

int a[5][4];

Its elements in turn one-dimensional arrays of the type int[4].

The expression *begin( a ) yields a reference to the first element of the array of the type int ( & )[4]. Used in this statement

 cout << *begin(a);

the expression is implicitly converted to a pointer to its first element of the type int * and equivalent to &a[0][0].

On the other hand the expression begin( a ) has the type int ( * )[4].

The address of the whole two-dimensional array coincides with the address of its first element, one dimensional array, that in turn coincides with the address of the first element of the one-dimensional array. though the used expressions have different types.

  • Related