Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
is it possible to write 2-d array in a different syntax other than array[i][j]?
example: if i have array[4][4], is it possible to type array[16] instead of the usual way? is it considered as a 2-d array?
Posted

Quote:
example: if i have array[4][4], is it possible to type array[16] instead of the usual way?
Yes , it is possible.


Quote:
is it considered as a 2-d array?
Nope, however you (that is your code) may consider it as a 2-d array, e.g.
C
#define ROWS  4
#define COLS  4
int x[ROWS * COLS];
int r,c;
for (r = 0; r < ROWS; ++r)
{
  for( c = 0; c < COLS; ++c)
  {
     int index = r * COLS + c;
     x[index] = r == c ? 1 : 0;
  }
}


The above code uses the array x as a 4x4 matrix, assigning it the identity matrix components.
 
Share this answer
 
v2
Yes...but...it's not necessarily a good idea.
In essence, all memory is just "chunks" of RAM, and the various structures we put in our code are ultimately "mapped" to those chunks.
So while
C++
int arr2p[4][4];

and
C++
int arr1p[16];

Will probably occupy the same amount of memory, the second is not a 2D array, although (as CPalini as shown) it can be accessed in a similar way.

But it's not a good idea. Partly because the code is a lot less obvious to the next person to have to modify it, and partly because the compiler is probably a lot better at optimising the code for the array access than you are! :laugh:
And...some systems can do bounds checking to ensure that you don't "run off the end" of a row in a 2D array by mistake, which would have to be manually done in a 1D array treated as a 2D.

Generally, if you need a 2D array, declare it as a 2D array so that the code is more maintainable. If you need to "run" from the end of one row to the beginning of the next for performance reasons, then use pointers instead of indexes anyway.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900