带有二维数组的指针 [英] Pointers with two dimensional array
问题描述
请考虑以下代码
#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 中,多维数组只是数组的数组.在许多情况下,使用数组的名称衰减"为指向该数组第一个元素的指针.这就是您的两个打印语句中发生的情况.第一种情况:
Arrays aren't pointers, and in C, a multidimensional array is just an array of arrays. In many contexts, using the name of an array "decays" into a pointer to the first element of that array. That's what happens in both of your print statements. In the first case:
printf("Base address of array:%p\n",a);
a
成为指向数组第一个元素的指针 - 即指向数组第一行的指针.在你的情况下,这意味着你得到一个 int (*)[2]
类型的指针.
a
becomes a pointer to the first element of the array - that is, a pointer to the first row of your array. In your case, that means you get a pointer of type int (*)[2]
.
第二种情况:
printf("Value at the Base address:%p\n",*a);
同样的衰减发生了,但随后你取消了该指针的引用.这意味着您取消引用 int (*)[2]
指向第一行的指针,再次为您留下数组(第一行).该数组本身衰减为指向它的第一个元素的指针,为您提供一个结果int *
指针(指向第一行的第一个元素).
The same decaying happens, but then you dereference that pointer. That means you dereferenced that int (*)[2]
pointer to the first row, leaving you with an array again (the first row). That array itself decays into a pointer to its first element, giving you a resulting int *
pointer (to the first element of the first row).
在这两种情况下,地址是相同的,因为这就是数组在内存中的布局方式.如果我们说你的二维数组从地址 0
开始,它看起来像这样(假设是一个 4 字节的 int
类型):
In both cases the address is the same, since that's how the array is laid out in memory. If we said your 2D array started at address 0
, it would look like this (assuming a 4 byte int
type):
Address Value
0 1
4 2
8 3
12 4
第一行的地址和第一行的第一个元素的地址都是0
.
The address of the first row and the address of the first element of the first row are both 0
.
这篇关于带有二维数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!