user8116022
user8116022

Reputation:

Cycling through columns vs cycling through rows when working with 2D arrays

I am trying to understand this code. The first thing that's confusing to me is that in the second line of code I believe they are creating an array of pointers and the plan is that those pointers are going to point to arrays.

I know that the computer doesn't care but to me, it's most logical to have the array of pointers be horizontal and then each array can drop down from the points on that horizontal line.

So, is it reasonable to have "dynamicArray = new int *[COLUMNS];" instead?

int **dynamicArray = 0;

//memory allocated for elements of rows.

dynamicArray = new int *[ROWS] ;

//memory allocated for elements of each column.

for( int i = 0 ; i < ROWS ; i++ )  
dynamicArray[i] = new int[COLUMNS];

//free the allocated memory

for( int i = 0 ; i < ROWS ; i++ )  
delete [] dynamicArray[i] ;  
delete [] dynamicArray ;

EDIT: I thought about this more and the thing that I am getting tripped up on a lot is that I think about the rows and columns in the wrong way.
dynamicArray = new int *[ROWS];
I understand this to be an array of pointers and each pointer is pointing to a column. The number of elements in each column is equal to the number of rows (columns have one vertical element for each row in our 2D array). Am I understanding this right?
I also get tripped up a lot when I need to use nested for loops to initialize a 2 D array.

Upvotes: 0

Views: 39

Answers (1)

realharry
realharry

Reputation: 1575

Rows/columns are symmetric/interchangeable, and as you say, "the computer doesn't care". Having said that, why do you think "it's most logical to have the array of pointers be horizontal and then each array can drop down from the points on that horizontal line"?

I would think the other way. I would find it much easier to "visualize" rows of horizontal objects (after all, we write horizontally (say, an array of chars), and the lines/rows go top to bottom (say, an array of arrays)). I think the code is more natural (to me) than what you suggest.

The point is, we all think differently, and at the end of the day, ROWS/COLUMNS are just variables, which could have been easily written as X/Y or V/H or W/H or whatever.

Upvotes: 1

Related Questions