Edit: I’ve removed the faster/more efficient from the question title as it was misleading..my intention was not optimisation but understanding arrays. Sorry for the trouble!
int array[10][10], i, j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[i][j];
}
Versus
int array[10][10], i, j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
std::cin>>array[j][i];
}
I’m pretty sure the answer has to do with how arrays are implemented on a hardware level; that the [ ][ ] syntax is just a programmer’s abstraction to aid visualisation/modelling. However, I forgot which of the above code accesses the memory block sequentially from start till end…
Thanks for all the answers…
Just to confirm my understanding, does this mean the first code is equivalent to
int array[10][10], k;
for(k=0;k<100;k++)
{
std::cin>>*(array+k);
}
Aside from the fact that waiting on getting user input will be signifficantly slower than the array access, the first one is faster.
Check out this page on 2D array memory layout if you want more background on the subject.
With the second one you are checking
A[0], A[10] ... A[1], A[11].The first is going sequentially
A[0], A[1], A[2] ..