gpt4 book ai didi

c - 这样用指针访问数组?

转载 作者:行者123 更新时间:2023-11-30 18:44:29 24 4
gpt4 key购买 nike

它基本上是通过指针将数组传递给函数。然后它打印出数组中的每个元素。我试图理解一行非常具体的指针,因为我的类(class)以前从未做过这样的例子。完成介绍后,我从未在指针主题中遇到过这个,因此我感到困惑。谢谢。

main( )
{
inta[3][4] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 0, 1, 6
} ;
display ( a, 3, 4 ) ;
show ( a, 3, 4 ) ;
print ( a, 3, 4 ) ;
}


display ( int*q, introw, intcol )
{
inti, j ;
for ( i= 0 ; i< row ; i++ )
{
for ( j = 0 ; j < col ; j++)
printf("%d ",*(q+i*col+j)); // THIS is the line Im trying to understand

printf( "\n" ) ;
}
printf("\n" ) ;
}

最佳答案

让我们将二维数组视为单个数组:

-------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | 1 | 6 |
-------------------------------------------------
^
index 0

如果我们仔细看看表达式(q+i*col+j):

q + (0 * 4) + 0 = 0th index
q + (0 * 4) + 1 = 1st index
q + (0 * 4) + 2 = 2nd index
q + (0 * 4) + 3 = 3rd index
^ ^
i j

打印第一行后,i 变为 1:

-------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | 1 | 6 |
-------------------------------------------------
^
4th index

q + (1 * 4) + 0 = 4
q + (1 * 4) + 1 = 5
q + (1 * 4) + 2 = 6
q + (1 * 4) + 3 = 7
^ indices

如您所见,这指向下一行。

i 变为 2:

-------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | 1 | 6 |
-------------------------------------------------
^

q + (2 * 4) + 0 = 8
q + (2 * 4) + 1 = 9
q + (2 * 4) + 2 = 10
q + (2 * 4) + 3 = 11
^ indices

等等。希望这有帮助

关于c - 这样用指针访问数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57844865/

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