1

I'm jumping into C++11 from C(ANSI). It's a strange world indeed.

I'm trying to come to grips with the following:

int tbl[NUM_ROWS][NUM_COLS] = { 0 };
for (auto row : tbl)
  for (auto col : row) // ERROR - can't iterate over col (type int *)
    // do stuff

The rational here, I'm guessing, is equivalent to the difference between (in C):

int v[] = { 1, 2, 3, 4, 5 };
int *u = v;
// (sizeof v) != (sizeof u);

However, I don't quite see how the following works:

int tbl[NUM_ROWS][NUM_COLS] = { 0 };
for (auto &row : tbl) // note the reference
  for (auto col : row)
    // do stuff

Logically, I'm thinking auto gets typed to int * const - thats what an "array" variable is, a constant pointer to a (possibly) non-constant element. But how is this any more iteratable than a normal pointer? Or, since row is a reference, it's actually typed to int [NUM_COLS], just as if we declared row as int row[NUM_COLS]?

1 Answer 1

11

There are no "multi-dimensional arrays" in C++. There are only arrays. However, the element type of an array can itself be an array.

When you say for (auto x : y), then x is a copy of the range element. However, arrays cannot be copied, so that is not valid when y is an array-valued array. By contrast, it is perfectly fine to form a reference to an array, which is why for (auto & x : y) works.

Maybe it helps to spell out the types:

int a[10][5];  // a is an array of 10 elements of int[5]

for (int (&row)[5] : a)
    for (int & cell : row)
        cell *= 2;
Sign up to request clarification or add additional context in comments.

3 Comments

Ya I know there's no multidimensional arrays - its just easier than saying arrays of arrays of ....In anycase, you are correct, arrays cannot be copied - attempts at assignment just copies the address of the first element. OK so, this is a fundamental difference on how a reference isnt just a constant pointer (even if they are internally implemented as such); a reference of an array acts like an array, and not just a reference of a pointer to an element
@user70869: Arrays are not pointers. Arrays are arrays. (And they're definitely not "constant pointers". You might be thinking of prvalues.)
Ya, arrays certainly arn't pointers. I was saying references weren't just like constant pointers (top-level const).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.