Why is the memory of a 2d array accessed by two parameters and not just by one (ignoring pointers).Why is it that the memory diagram is in terms of rows and columns and not straight (horizontal),Further more why is it said that 2d array is a array of arrays but i dont get that .
Share
It’s about convenience. Sure, the memory’s actually all sequential, but sometimes one wants to be able to access things with two indices (e.g. implementing matrices).
Consider a 3×3 array. It’s convenient to think of the memory like this:
But in memory, it of course really looks like this:
We just split it up into rows so that we can easily understand it as two-dimensional. We access it with two parameters because we want to, because that’s convenient for our code. The language provides this implementation, which makes it possible to access via two indices, even though under the covers it’s linear and could be accessed with one index.
This picture should also help you understand why it can be considered an array of arrays. Here’s a slightly modified picture, for emphasis:
As you can see, there are really three one-dimensional arrays there. So, when you write
array[1], you are referring to the second one-dimensional component of the full two-dimensional array, i.e. the second group of three in memory. Adding a second index,array[1][2]takes the third element of that one-dimensional array, getting you down to a single element of the two-dimensional array as desired.