Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 756
Derek Avatar asked Feb 20 '13 21:02

Derek


People also ask

How do you access multidimensional arrays?

Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP. Elements can be accessed using dimensions as array_name['first dimension']['second dimension']. Elements can be accessed using for loop. Elements can be accessed using for each loop.

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];

What is the syntax for multidimensional array in C?

The general form of declaring N-dimensional arrays is:data_type array_name[size1][size2]....[sizeN]; data_type: Type of data to be stored in the array. array_name: Name of the array. size1, size2,… ,sizeN: Sizes of the dimension.


2 Answers

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];
like image 186
Andrew Rasmussen Avatar answered Nov 07 '22 23:11

Andrew Rasmussen


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
}
like image 41
user2093113 Avatar answered Nov 08 '22 01:11

user2093113