5

Following code snippet:

int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
int(&row)[4] = ia[1];

enter image description here

I can't get my head around why this particular code is valid. For my current understanding I don't have a rational explanation. Can someone help me out with that? My problem is with &row which doesn't seem to reference anywhere. My only explanation is that this has to be valid because its an initialisation.

I've got the following explanation from my book:

.... we define row as a reference to an array of four ints

Which array? The one we are about to initialise?

HansMusterWhatElse
  • 671
  • 1
  • 13
  • 34

3 Answers3

13
 int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };

Is an array of 3 elements, each element is an array of 4 ints.

int(&row)[4] = ia[1];

Here the int(&row)[4] part declares a reference named row that can reference an array of 4 ints. the = ia[1] initializes it to reference the second element in the ia array, which is an array of 4 ints.

nos
  • 223,662
  • 58
  • 417
  • 506
  • "Here the int(&row)[4] part declares a reference named row that can reference an array of 4 ints." - this means it just can but it doesn't? Or does it point to the array which is getting initalised? – HansMusterWhatElse Nov 05 '15 at 08:16
  • 1
    @KingJulian It can and does, you initailize it (the `= ia[1]` part) to reference (or point to if you want, but the wording "point to" would normally be used with a pointer, not a reference) an array of 4 ints. Perhaps you need to read through e.g. [this](http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in). – nos Nov 05 '15 at 08:20
6
int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };

ia is an array of 3 arrays of 4 int each.

ia[0] is { 0, 1, 2, 3 }.

ia[1] is { 4, 5, 6, 7 }.

ia[2] is { 8, 9, 10, 11 }.

I don't quite understand why you say we would be "about to initialize" it -- at this point, ia is completely initialized.

int(&row)[4] = ia[1];

Spiral rule (start with the identifier...):

row

...is a...

(&row)

...reference...

(&row)[4]

...to an array of four...

int(&row)[4]

...int...

= ia[1];

...initialized by ia[1] (because you have to initialize a reference, no way around it).

So row is now a reference to ia[1], which is of type "array of four int". That's all there is to it.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
0

(&row)[4] means that it can reference to an array of 4 elements and ia[1] is a row from the 2d array ia[][] that contains 4 elements, hence it works fine.

Aditya Sanghi
  • 289
  • 1
  • 3
  • 18