iterate through a 2D array returned by a function

assuming i know the length of my dynamically created 2D array, how do i iterate through it?

the array is returned from the following function.

 
  int ** getArray()
1
2
3
4
5
6
7
8
9
10
11
12
13
for (int i = 0; i < ROW; i++)
{
	for (int j = 0; j < COL; j++)
	{
		// typical array element is *(ary[i]+j));
		// where ary is the array 
	}
}	
//and don't forget to clean up before exit ... 
for (i = 0; i < ROW; i++) {
  delete(ary[i]);

delete [] ary; 


why this because in a pointer of pointer representation of 2D array we first allocate memory for each row starting from the first element; and then, for each row, starting from the first element we allocate memory according to the size of the columns
Last edited on
Hello jessica1234,

You could try something like this:

1
2
3
4
5
6
7
for (int i = 0; i < firstDimensionSize; i++)
{
	for (int j = 0; j < secondDimensionSize; j++)
	{
		array[i][j]  //  i will loop through the rows and j will loop through the columns.
	}
}


You will need to expand on the code in the second for loop, but it is the basic idea.

Hope that helps,

Andy
hi andy,

first of all, how do I declare the array[][] to catch the return int** from my function?

int[][] array = getArray()

give me compilation error.

int ** getArray()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int** ary; 
ary = new(int* [ROW]);
for(int i = 0; i < ROW; i++)
{
	ary[i] = new int[COL];
}
//to use the array:

for (int i = 0; i < ROW; ++i) {   // for each row
  for (int j = 0; j < COL; ++j) { // for each column
    ary[i][j] = 1;
  }
}
//finally, to delete before exit:
for (int i = 0; i < ROW; i++) {
  delete[] ary[i];
}
delete[] ary;
Topic archived. No new replies allowed.