Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the standard define the type for `a[i]` where `a` is `T [M][N]`?

I, very occasionally, make use of multidimensional arrays, and got curious what the standard says (C11 and/or C++11) about the behavior of indexing with less "dimensions" than the one declared for the array.

Given:

int a[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};

Does the standard says what type a[1] is, or a[0][1], is it legal, and whether it should properly index sub-arrays as expected?

auto& b = a[1];

std::cout << b[1][1];
like image 646
pepper_chico Avatar asked Aug 01 '13 13:08

pepper_chico


2 Answers

m[1] is just of type int[2][2]. Likewise m[0][1] is just int[2]. And yes, indexing as sub-arrays works the way you think it does.

like image 182
Drew McGowen Avatar answered Oct 11 '22 13:10

Drew McGowen


Does the standard define the type for a[i] where a is T [M][N]?

Of course. The standard basically defines the types of all expressions, and if it does not, it would be a defect report. But I guess you are more interested on what that type might be...

While the standard may not explicitly mention your case, the rules are stated and are simple, given an array a of N elements of type T, the expression a[0] is an lvalue expression of type T. In the variable declaration int a[2][2] the type of a is array of 2 elements of type array of two elements of type int, which applying the rule above means that a[0] is lvalue to an array of 2 elements, or as you would have to type it in a program: int (&)[2]. Adding extra dimensions does not affect the mechanism.

like image 30
David Rodríguez - dribeas Avatar answered Oct 11 '22 15:10

David Rodríguez - dribeas