我有以下代码:
#include<stdio.h> void main() { int * a; int arr[2]; arr[1] = 213 ; arr[0] = 333 ; a = &arr ; printf("\narr %d",arr); printf("\n*arr %d",*arr); printf("\n&arr %d",&arr); printf("\n%d",a[1]); }在运行此简单程序时,我得到的输出如下:
On running this simple program i get the output as follows :
arr -1079451516 *arr 333 &arr -1079451516 213为什么arr和& arr都给出相同的结果?我可以理解arr是某个内存位置,而* arr或arr [0]是存储在该位置的值,但是为什么& arr和arr相同?
Why is it that both arr and &arr give the same result ? I can understand that arr is some memory location and *arr or arr[0] is the value stored at the position, but why is &arr and arr same ?
推荐答案几乎每次使用数组类型的表达式时,它都会立即衰减"到第一个元素的指针. arr成为类型为int*的指针,而该指针实际上是传递给printf的指针. &arr是类型为int (*)[2]的指针(指向两个int的数组的指针).这两个指针的地址相同,因为它们都指向数组的开头.
Almost any time you use an expression with array type, it immediately "decays" to a pointer to the first element. arr becomes a pointer with type int*, and this pointer is what's actually passed to printf. &arr is a pointer with type int (*)[2] (pointer to array of two ints). The two pointers have the same address, since they both point at the beginning of the array.
(数组到指针转换的一个显着例外是sizeof自变量.)
(One notable exception to the array-to-pointer conversion is in a sizeof argument.)
更多推荐
关于C语言中的数组名称和数组地址
发布评论