Access a whole row of a multidimensional array in C ++

How to access an entire row of a multidimensional array? For instance:

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 gives an error:

curly braces are needed to initialize the array

I know I can get a string using a FOR loop, but I'm curious if there was a more obvious solution.

+4
source share
3 answers

This is not how arrays / pointers work in C ++.

This array is stored somewhere in memory. To refer to the same data, you need a pointer pointing to the beginning of the array:

 int* temp = logic[2]; 

Or, if you need a copy of this array, you will 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 are using C ++, if you want to not worry about all these memory materials and pointers, you should use std::vector<int> for arrays with dynamic size and std::array<int> for arrays of static size .

 #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]; 
+5
source

Also, like decomposing an array into a pointer, you can also bind it to a link:

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

One of the advantages of this is that you can use it in a C ++ 11 loop for loops:

 for (auto t : temp) { // stuff } 
+4
source

Direct assignment will not work. C ++ does not allow this. In the best case, you can assign them to indicate the same data - int *temp = logic[2] . You will need a for loop or something like below.

I believe this will work:

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

But I usually suggest using std::vector or std::array instead.

+2
source

All Articles