Originally Posted by
narendrav
what i don't understand is that when i created the array,
i only gave it 2 columns.
But when i wrote arr[0][3] , it still printed a value.
How did this happen..??
Imagine if you had declared arr as:
Code:
int arr[6] = {1, 2, 3, 4, 5, 6};
You could still access arr as if it were a 2D array, e.g.,
Code:
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 2; ++j)
{
printf("%d ", arr[i * 2 + j]);
}
printf("\n"0;
}
So, the same maths applies here: arr[0][3] in your example would be arr[0 * 2 + 3], i.e., arr[3] in my example, which has the value of 4. We get the multiplier of 2 because each increment of the first index "skips" 2 elements, i.e., the number of elements in one of the conceptual "inner arrays".
That said, you should be careful here because if you were to miscalculate, you risk accessing the array out of bounds, and it would be harder to see at a glance because you are already intentionally accessing the inner arrays out of bounds (but still within the bounds of the array overall).