gpt4 book ai didi

c - 带二维数组的指针

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:57 24 4
gpt4 key购买 nike

请考虑以下代码

#include <stdio.h>
#define ROW_SIZE 2
#define COL_SIZE 2

int main()
{
int a[ROW_SIZE][COL_SIZE]={{1,2},{3,4}};

// Base address:Pointer to the first element a 1D array
printf("Base address of array:%p\n",a);

//The value at the base address: should be the address of 1st 1D array
printf("Value at the Base address:%p\n",*a);

return 0;
}

获得的输出:

Sample Output:
Base address of array:0xbff77434
Value at the Base address:0xbff77434

不知何故,我无法理解二维数组的基地址和基地址处的值,而基地址的值又与一维数组的地址相同。请解释。

最佳答案

数组不是指针,在 C 语言中,多维数组只是数组的数组。在许多情况下,使用数组名称会“衰减”为指向该数组第一个元素的指针。这就是您的两个打印语句中发生的情况。在第一种情况下:

printf("Base address of array:%p\n",a);

a 成为指向数组第一个元素的指针 - 即指向数组第一行的指针。在你的例子中,这意味着你得到了一个 int (*)[2] 类型的指针。

第二种情况:

printf("Value at the Base address:%p\n",*a);

同样的衰减发生了,但是你取消引用了那个指针。这意味着您取消引用指向第一行的 int (*)[2] 指针,再次为您留下一个数组(第一行)。该数组自身 衰减为指向它的 第一个元素的指针,为您提供一个结果int * 指针(指向第一行的第一个元素) .

在这两种情况下,地址是相同的,因为这就是数组在内存中的布局方式。如果我们说你的二维数组从地址 0 开始,它看起来像这样(假设一个 4 字节的 int 类型):

 Address       Value
0 1
4 2
8 3
12 4

第一行的地址和第一行第一个元素的地址都是0

关于c - 带二维数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53965775/

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