Alex Rivera | Logout

Accessing an entire row of a multidimensional array in C++

Asked 2013-02-20T21:41:58.557
8

How would one access an entire row of a multidimensional array? For example:

int logic[4][9] = {
    {0,1,8,8,8,8,8,1,1},
    {1,0,1,1,8,8,8,1,1},
    {8,1,0,1,8,8,8,8,1},
    {8,1,1,0,1,1,8,8,1}
};

// I want everything in row 2. So I try...
int temp[9] = logic[2];

My attempt throws the error:

array initialization needs curly braces

I know I can retrieve the row using a FOR loop, however I'm curious if there was a more obvious solution.

Edit
Report

1 Answer

5

As well as decaying the array to a pointer, you can also bind it to a reference:

int (&temp)[9] = logic[2];

One advantage of this is it will allow you to use it C++11 range-based for loops:

for (auto t : temp) {
  // stuff
}
answered 2013-02-20T21:53:43.283

Your Answer