示例1:
int A[4][3];
int get_value(int A[4][3], int i, int j)
{
return A[i][j];
}
gcc -O1 -S -m32 array1.c
get_value:
pushl %ebp
movl %esp, %ebp
movl 12(%ebp), %eax //eax = i
leal (%eax,%eax,2), %eax //eax= 3*eax = 3*i
addl 16(%ebp), %eax //eax = 3*i+ j
movl 8(%ebp), %edx //edx =&A[0][0],数组的起始地址
movl (%edx,%eax,4), %eax //eax= (4*(3*i+j) +&A[0][0])内存地址的值
popl %ebp
ret
从中可以看出,二维数组A[M][N]的元素A[i][j]地址的计算公式:(i*N + j)*sizeof(数组元素的类型)+&A[0][0]
示例2:
#define N 16
typedef int fix_matrix[N][N];
int fix_prod_ele (fix_matrix A, fix_matrixB, int i, int k)
{
int j;
int result = 0;
for (j = 0; j < N; j++)
result+= A[i][j] * B[j][k];
return result;
}
gcc -O1 -S -m32 array2.c
fix_prod_ele:
pushl %ebp
movl %esp, %ebp
pushl %esi
pushl %ebx
movl 16(%ebp), %eax //eax = i
sall $6, %eax //i左移6位
movl %eax, %esi //esi = I<< 6=i*64
addl 8(%ebp), %esi //esi =A+64*i
movl 20(%ebp), %eax //eax = k
sall $2, %eax //eax = 4*k
movl 12(%ebp), %edx //edx = B
addl %eax, %edx //edx = B+4*k
movl $0, %ebx //ebx = 0 =result
movl $1, %ecx //ecx = 1 = j+1
.L2:
movl (%edx), %eax //eax=B[j][k]
imull -4(%esi,%ecx,4), %eax//eax = (A+64*i+4*(j+1)-4)地址的值*B[j][k]=A[i][j]*B[j][k]
addl %eax, %ebx //result += A[i][j]*B[j][k]
addl $1, %ecx //++j
addl $64, %edx //edx = edx +64
cmpl $17, %ecx //比较j+1和17
jne .L2 //如果不相等,跳转到L2,继续循环
movl %ebx, %eax //eax = result
popl %ebx
popl %esi
popl %ebp
ret