> How can I convert a 2D array to a 1D array in C++?

How can I convert a 2D array to a 1D array in C++?

Posted at: 2014-12-18 
I need to use the first row of a 2D array in a function.

a[7][7] is my 2D array. can i just use a[1] in my function? it doesn't seem to be working.

a[1] is a pointer to the second row of the array.

If you want to traverse your array as if it were sequential (which it is in memory), you have to use pointer arithmetic.

To access the first row (index 0) of the array, you could pass a[0] to the function.

Say, the parameter in the function receiving the pointer address is b[] or *b .

Then you want to traverse the elements by adding to the variable.

To get to the 2nd element (index1) you would say

b[1] = x;

or

*(b+1) = x;

To traverse the full 2d array using pointer arithmetic you multiply the row by the number of columns, then add the column.

so a[3][4] is the same as *(a + ( (3*7) + 4))

By dereferencing the pointer you are accessing the value it points to in memory, not the memory address.

I hope this code helps a bit ...

#include

using namespace std;

void display(const int ar[], const int iElements)

{

for (int i = 0; i < iElements; i++) {

cout << ar[i] << " ";

}

}

int main()

{

int a[10][7] = { // 10 rows, 7 columns, each

{0,0,0,0,0,0,0},

{1,1,1,1,1,1,1},

{2,2,2,2,2,2,2},

{3,3,3,3,3,3,3},

{4,4,4,4,4,4,4},

{5,5,5,5,5,5,5},

{6,6,6,6,6,6,6},

{7,7,7,7,7,7,7},

{8,8,8,8,8,8,8},

{9,9,9,9,9,9,9}



};

for (int i = 0; i < 10; i++) {

display(a[i], 7);

cout << endl;

}

}

I need to use the first row of a 2D array in a function.

a[7][7] is my 2D array. can i just use a[1] in my function? it doesn't seem to be working.