开发者

About array names and addresses of arrays in C

I had the following code :

#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

Why is it that both arr and &arr give the same result ? I can understand t开发者_Go百科hat arr is some memory location and *arr or arr[0] is the value stored at the position, but why is &arr and arr same ?


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.

(One notable exception to the array-to-pointer conversion is in a sizeof argument.)


They're the same by definition (i.e. because the language designers chose them to mean the same thing.)


arr is treated like a constant pointer, it evaluates to the memory address where your integer array is located. The memory location arr evaluates to cannot be changed. It does not make sense to ask for the address of arr, because there is no place in memory where this constant pointer is stored.

The non-constant pointer that you declared, a, is a location in memory that can hold a pointer (the location of something else in memory, in this case the start of the arr array). Therefore &a will evaluate to a memory address other than -1079451516. The pointer "a" has a memory address allocated for it because you could change a to point to something else, storing that address in the pointer a. arr can never be re-defined in this function so there is no need to store it in memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜