2

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 ?

2

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

When I do sizeof( a ) i get 4 * 2 = 8 . However doing sizeof( &a ) gives me 4 . Why is it so ?
@S..K: a or arr? If those are the same identifiers as in your code, it makes a difference. Assuming you meant arr, or that a is really an array, this is because the array-to-pointer conversion does not happen in sizeof, so it can give a useful size of an array. In the second case, sizeof is giving the size of a pointer.
@above : my apologies. I intended to mean arr and not a. Thank you for clearing my doubts and may I assume this is what you have meant in the last line of your answer regarding sizeof() ?
Why don't we have to de-reference the pointer array "a[1]" to get value 213?
2

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.