Why are 2-D arrays reversed?

Chris Katko ckatko at gmail.com
Wed Oct 10 22:26:40 UTC 2018


On Wednesday, 10 October 2018 at 16:00:42 UTC, Steven 
Schveighoffer wrote:
> On 10/10/18 9:22 AM, Chris Katko wrote:
>> int[][] data =
>>      [
>>          [1, 0, 1, 0, 0],
>>          [1, 0, 1, 0, 0],
>>          [1, 0, 1, 1, 1],
>>          [1, 0, 0, 1, 0],
>>          [5, 1, 1, 1, 0]
>>      ];
>> 
>> when drawn with data[i][j], prints the transpose of "data":
>> 
>> [1, 1, 1, 1, 5]
>> [0, 0, 0, 0, 1]
>> [1, 1, 1, 0, 1]
>> [0, 0, 1, 1, 1]
>> [0, 0, 1, 0, 0]
>> 
>> So, if I flip [i][j] and print a row of "j's", it'll be 
>> correct. It's very confusing and counter-intuitive to have to 
>> remember to swap i and j every time I use an array.
>> 
>> I guess when I load data from files, the i/j are already 
>> swapped and stay consistent, but when using an array in source 
>> code, they have to be flipped.
>
> I'm not sure what code you are using, but it prints out just 
> fine for me:
>
> https://run.dlang.io/is/hrA0tj
>
> -Steve

Ah, here's a simple example:

int[][] data3 =
	[
		[1, 0, 1, 0, 0],
		[1, 0, 1, 0, 0],
		[1, 0, 1, 1, 1],
		[1, 0, 0, 1, 0],
		[5, 1, 1, 1, 0]
	];

	for(int i = 0; i < 5; i++)
		{
		for(int j = 0; j < 5; j++)
			{
			write(data4[i][j]," ");
			}
		writeln();
		}

   1 0 1 0 0
   1 0 1 0 0
   1 0 1 1 1
   1 0 0 1 0
   5 1 1 1 0

I have to draw j's first. I have to iterate through the 
"y"/columns/j to get the the "x's" first.

I mean, I guess it makes sense if the outer-most array indexer 
refers to the inner-most "element".

Wait, this IS the same as C, isn't it? So maybe this is just a 
"new" problem for me since I rarely-if-ever use hardcoded 
arrays...

Maybe my brain is just melting.


More information about the Digitalmars-d-learn mailing list