0

Possible Duplicate:
How do I use arrays in C++?

would there be any Memory issues or execution issues or any merits or demerits of using 1D array of size 'mn' instead of using 2D array of size mxn ?

Community
  • 1
  • 1
Aragon
  • 1,551
  • 1
  • 15
  • 25

3 Answers3

2

In memory, they are represented exactly the same. The difference is semantic. If you're operating on a matrix, accesing an element as

x[i][j]

is more intuitive than

x[i*n + j]
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • wont there be any overhead for 2 dimenstional array while executing or accessing its elements? – Aragon Sep 10 '12 at 19:17
  • @user1660982 I highly doubt that. Write your code for readability first, and worry about performance only after measuring. – Luchian Grigore Sep 10 '12 at 19:27
  • There absolutely is an overhead for accessing the array as a 2D array. If you allocate the 2D array as an array of arrays, you could run into performance issues for large enough arrays. – Mike Bailey Sep 10 '12 at 21:14
  • Are you sure it's not i*n+j ? – bokan Sep 10 '12 at 21:14
  • @MikeBantegui can you back that up? – Luchian Grigore Sep 10 '12 at 21:15
  • @LuchianGrigore: Simple. Spatial locality. If you allocate as an array of arrays, you may not necessarily end up with two consecutive rows (e.g. i and i + 1) being allocated adjacent to each other. – Mike Bailey Sep 10 '12 at 21:19
  • @MikeBantegui ah, in that case, you're right, but I assumed it's a statically allocated array - i.e. `int x[10][10]`. Otherwise, accessing the elements like that wouldn't work. – Luchian Grigore Sep 11 '12 at 11:21
1

Both the arrays 1D and 2D are exactly the same in memory perspective. The only difference would be syntactically. 3D arrays would only be useful to design the logic around the problem.

e.g:

array x[m*n]
array x[m][n]

Both are same when we talk in terms of memory

Mike Aski
  • 9,180
  • 4
  • 46
  • 63
Mano Nandu
  • 11
  • 1
0

You can create the 2D array of int and a pointer to int.

Then you can set the pointer to the adress of the first element

int* singleDimention=&twoDimension[0][0];

If you process all items regardless of their 2D coordinates, it will be faster (slightly) to do it using one dimension array.

numItems=n*m;
for(i=0;i<numItems;i++){
    do stuff with singleDimention[i];
}
bokan
  • 3,601
  • 2
  • 23
  • 38