# Treating a 2D array as a 1D array....

Printable View

• 10-18-2007
John_L
Treating a 2D array as a 1D array....
Is it more efficient to treat a 2D array as a 1D array in C? If I had a 2D array, array[8][8] and I accessed it via a pointer arrayPtr++ for all 63 elements. As opposed to two for loops, doing array[i][j]. Or is there no difference at all? Is it better to do one or the other? Or are they both equal statements and it depends on what I feel like doing?

Code:

```**NOTE: this is just example code to illustrate my meaning, please don't comment on the code, I did not write it with the intent to compile or run it. 1) arrayPtr = &board[0][0]; for( i=0; i<63; i++ ) {   char ch = *arrayPtr++; } 2) for( i=0; i<8; i++ ) {   for(j=0; j<8; j++ )   {       char ch = board[i][j];   } }```
• 10-18-2007
matsp
Yes, that will do equivalent things.

--
Mats
• 10-18-2007
Cactus_Hugger
No, they will do two different things. Mostly because of:
Quote:

If I had a 2D array, array[8][8] and I accessed it via a pointer arrayPtr++ for all 63 elements.
8 * 8 == 64, not 63. There are 64 elements, but the last usable index is 63. However, your two code snippets differ in this respect. The first will make 63 iterations, the latter 64.

As to which is more efficient, it probably won't matter which you use. If you notice any problems, let a profiler tell you what's taking up processing time, and optimize there. Otherwise, I'd probably go with the second myself.
• 10-18-2007
Salem
• 10-18-2007
John_L
Cactus_Hugger: 0 - 63 is the same as 1 - 64.....
• 10-18-2007
matsp
Quote:

Originally Posted by John_L
Cactus_Hugger: 0 - 63 is the same as 1 - 64.....

Yes, _BUT_ Cactus_Hugger makes a good catch:
Code:

`for( i=0; i<63; i++ )`
will stop at 62, not 63.
Should be (i < 64) to be correct - sorry I missed that. Well spotted Cactus_hugger.

--
Mats
• 10-18-2007
brewbuck
Quote:

Originally Posted by John_L
Cactus_Hugger: 0 - 63 is the same as 1 - 64.....

But there are 64 elements. The particular indexing isn't the point.