问题描述
请考虑下面的一段code的
Please consider the following piece of code
#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
不知怎的,我没有理解二维数组的基址的概念,并在该基地的地址是inturn一个地址为一维数组是相同的值。请解释一下。
推荐答案
数组不是指针,在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
这篇关于用二维数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!