Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, which is the way to access a 2D array sequentially (memory block wise)

Tags:

c++

arrays

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);
}
like image 821
Yew Long Avatar asked May 21 '09 00:05

Yew Long


2 Answers

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] ..

like image 198
JensenDied Avatar answered Sep 22 '22 05:09

JensenDied


The first one has better spatial locality. Because the first subscript is the index of a subarray, and the second subscript is the element within that subarray; so when you fix i and vary the j's, you are looking at elements that are all within a subarray and thus are close together; but when you fix j and vary the i's, you are looking at elements that are 10 (the length of a subarray) apart, so are very spread out.

like image 31
newacct Avatar answered Sep 18 '22 05:09

newacct