1.20. ARRAYS
Access two-dimensional array as one-dimensional
We can be easily assured that it’s possible to access a two-dimensional array as one-dimensional array in
at least two ways:
#include <stdio.h>
char a[3][4];
char get_by_coordinates1 (char array[3][4], int a, int b)
{
return array[a][b];
};
char get_by_coordinates2 (char array, int a, int b)
{
// treat input array as one-dimensional
// 4 is array width here
return array[a4+b];
};
char get_by_coordinates3 (char array, int a, int b)
{
// treat input array as pointer,
// calculate address, get value at it
// 4 is array width here
return (array+a*4+b);
};
int main()
{
a[2][3]=123;
printf ("%d\n", get_by_coordinates1(a, 2, 3));
printf ("%d\n", get_by_coordinates2(a, 2, 3));
printf ("%d\n", get_by_coordinates3(a, 2, 3));
};
Compile^144 and run it: it shows correct values.
What MSVC 2013 did is fascinating, all three routines are just the same!
Listing 1.246: Optimizing MSVC 2013 x64
array$ = 8
a$ = 16
b$ = 24
get_by_coordinates3 PROC
; RCX=address of array
; RDX=a
; R8=b
movsxd rax, r8d
; EAX=b
movsxd r9, edx
; R9=a
add rax, rcx
; RAX=b+address of array
movzx eax, BYTE PTR [rax+r94]
; AL=load byte at address RAX+R94=b+address of array+a4=address of array+a4+b
ret 0
get_by_coordinates3 ENDP
array$ = 8
a$ = 16
b$ = 24
get_by_coordinates2 PROC
movsxd rax, r8d
movsxd r9, edx
add rax, rcx
movzx eax, BYTE PTR [rax+r9*4]
(^144) This program is to be compiled as C program, not C++, save it to a file with .c extension to compile it using MSVC