加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 具有二维阵列的指针

发布时间:2020-12-16 10:32:17 所属栏目:百科 来源:网络整理
导读:请考虑以下代码 #include stdio.h#define ROW_SIZE 2#define COL_SIZE 2int 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:%pn",a); //The value at the base
请考虑以下代码

#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:%pn",a);

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

   return 0;
}

获得的产出:

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

不知何故,我无法理解2D数组的基地址的概念和基地址的值,该地址是1D数组的地址相同.请解释.

解决方法

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

printf("Base address of array:%pn",a);

a成为指向数组第一个元素的指针 – 即指向数组第一行的指针.在你的情况下,这意味着你得到一个类型为int(*)[2]的指针.

在第二种情况:

printf("Value at the Base address:%pn",*a);

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

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

Address       Value
    0            1
    4            2
    8            3
   12            4

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读