gpt4 book ai didi

将一维数组的索引转换为访问二维数组

转载 作者:行者123 更新时间:2023-11-30 16:32:18 26 4
gpt4 key购买 nike

void dgem(int n, double *A, double *B, double *C)
{

for(int i = 0; i < n; ++i){
for(int j = 0; j < n; j++){

double cij = C[i+j*n]; /* cij = C[i][j] */

for(int k = 0; k < n; k++){
cij += A[i+k*n] * B[k+j*n]; /*cij = A[i][k]*b[k][j]*/
C[i+j*n] = cij; /* C[i][j] = cij */
}
}
}

}

此代码来自 Computer_Organization_and_Design_5th

是吗? 双 cij = C[i+j*n];

据我所知,应该是C[i*n + j]

int main(void){

double A[4][4] = {1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16};
double * a = &A[0][0];

int n = 4;
printf("%f %f %f %f", *(*(A+1)+3), A[1][3], a[1*n + 3], a[1 + 3*n]); /*
when i == 1 and j == 3 */

return 0;

}

输出:

8.000000 8.000000 8.000000 14.000000

当我尝试使用 gcc 时,它没有意义......

最佳答案

以下声明

double cij = C[i+j*n]; 

是正确的。为了理解这一点,让我们假设 double ptr[3] = {1.5,2.5,3.5] ,其中 ptr 是三个 double 变量的数组。现在您将如何访问 ptr[0]ptr[1]

 ----------------------------------------
| 1.5 | 2.5 | 3.5 | 4.5 |
-----------------------------------------
0x100 0x108 0x116 0x124 0x132 <-- lets say starting address
LSB of ptr is 0x100
|
ptr

对于行= 1

ptr[row] == *(ptr + row * sizeof(ptr[row]))
2.5 == *(0x100 + 1*8)
2.5 == *(0x108)
2.5 == 2.5

从上面你不能有*(ptr*8 + row),它应该是*(ptr + row*8)

类似地,如果ptr是像double ptr[2][3]这样的2D数组,那么

ptr[行][列] == *( *(ptr + 行) + col*8)

同样,在您的情况下,有效的是 C[i + j*n] 而不是 C[i*n +j]

编辑:-你有一个像下面这样的二维数组

double A[4][4] = { {1,2,3,4} , {5,6,7,8} , {9,10,11,12} , {13,14,15,16} };

还有

double *a = &A[0][0];

现在看起来像

    A[0]          |   A[1]        |   A[2]           |   A[3]             |
-------------------------------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
-------------------------------------------------------------------------
0x100 0x108...................0x156.......................0x156 (assume that 0x100 is starting address of A)
A
a
LSB -->

现在,当您执行a[1*n + 3])时,其内部如何扩展

a[1*n + 3]) == *(a + (1*n + 3)  /*note that a is double pointer, it increments by 8 bytes
a[1*n + 3]) == *(0x100 + (1*4 + 3) *8)
a[1*n + 3]) == *(0x100 + 56)
== *(0x156)
== 8 /* it prints 8.000000 */

当你执行a[1+3*n])其内部如何扩展时

a[1+3*n]) == *(a + (1+3*n)*8)
a[1+3*n]) == *(0x100 + (1+3*4)*8)
a[1+3*n]) == *(0x100 + 96)
== *(0x196)
== 14 /* it prints 14.000000 */

当您执行*(*(A+1) +3))时,它会在内部扩展为

*(*(A+1) +3)) == *( *(0x100 +1*32) + 3*8) /* A+1 means increment by size of A[0] i.e 32 */ 
*(*(A+1) +3)) == *( *(0x132) + 24)
*(*(A+1) +3)) == *( 0x132 + 24 ) == *(156)
*(*(A+1) +3)) == 8 /*it prints 8.000000 */

当您执行 A[1][3] 时,与上述情况相同。

关于将一维数组的索引转换为访问二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50214577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com