S..K
S..K

Reputation: 2024

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 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 ?

Upvotes: 2

Views: 235

Answers (3)

Joseph Stine
Joseph Stine

Reputation: 1022

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.

Upvotes: 0

aschepler
aschepler

Reputation: 72401

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.)

Upvotes: 4

NPE
NPE

Reputation: 500437

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

Upvotes: 2

Related Questions