Derek
Derek

Reputation: 809

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

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.

Upvotes: 8

Views: 26238

Answers (3)

Andrew Rasmussen
Andrew Rasmussen

Reputation: 15099

That's not how arrays/pointers work in C++.

That array is stored somewhere in memory. In order to reference the same data, you'll want a pointer that points to the the beginning of the array:

int* temp = logic[2];

Or if you need a copy of that array, you'll have to allocate more space.

Statically:

int temp[9];
for (int i = 0; i < 9; i++) {
    temp[i] = logic[2][i];
}

Dynamically:

// allocate
int* temp = new int(9);
for (int i = 0; i < 9; i++) {
    temp[i] = logic[2][i];
}

// when you're done with it, deallocate
delete [] temp;

Or since you're using C++, if you want to not worry about all this memory stuff and pointers, then you should use std::vector<int> for dynamically sized arrays and std::array<int> for statically sized arrays.

#include <array>
using namespace std;

array<array<int, 9>, 4> logic = {
  {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}
}};

array<int, 9> temp = logic[2];

Upvotes: 12

user2093113
user2093113

Reputation: 3560

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
}

Upvotes: 5

Bernhard Barker
Bernhard Barker

Reputation: 55589

A direct assignment won't work. C++ does not allow that. At best you'll be able to assign them to point to the same data - int *temp = logic[2]. You'll need a for loop or something like the below.

I believe this would work:

int temp[9];
memcpy(temp, logic[2], sizeof(temp));

But I'd generally suggest using std::vector or std::array instead.

Upvotes: 2

Related Questions