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 ?

Answers


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


Need Your Help

How to look for a text in an input

python string input integer

I am having a problem with this very simple calculator script. If a user enters a letter or a word (such as: s, the), the system would crash. My idea is to make it print:

How to pass objects to functions in C++?

c++ pointers pass-by-reference pass-by-value c++-faq

I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++.