2

Following program would state my doubt clearly I think,so I posted the program:

 #include <stdio.h>
int main() {

        int a[]={1,2,3,4,5};
        if(&a[0] == a)
                printf("Address of first element of an array is same as the value of array identifier\n");
        if(&a == a)
                printf("How can a value and address of an identifier be same?!");

        return 0;
}

This is the link to output: http://ideone.com/KRiK0

ZoomIn
  • 1,237
  • 1
  • 17
  • 35
  • possible duplicate of [Is array name a pointer in C?](http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c) – Jeff Mercado Feb 23 '12 at 05:52

4 Answers4

4

When it is not the subject of the sizeof or unary & operators, an array evaluates to a (non-lvalue) pointer to its first element.

So &a is the address of the array a, and a evaluates to the address of the first element in the array, a[0].

That the address of the array and the address of the first element in the array are the same is not surprising (that is, they point to the same location even though they have different types); the same is true of structs as well. Given:

struct {
    int x;
    int y;
} s;

Then &s and &s.x point to the same location (but have different types). If converted to void * they will compare equal. This is exactly analogous with &a and &a[0] (and consequently just a).

caf
  • 233,326
  • 40
  • 323
  • 462
  • Just to conclude after going through all the links - a stores address of a[0].Since array a starts with a[0] address of a is address of first element. – ZoomIn Feb 23 '12 at 08:39
  • @ZoomIn: `a` does not *store* the address of `a[0]` - `a` "stores" the entire array contents. `a` *evaluates to* the address of `a[0]` when you use it in almost all contexts. – caf Feb 23 '12 at 08:41
0

If I get your question right. Your int a[]={1,2,3,4,5}; I believe only stores the address of element 0 so putting this if(&a[0] == a) is probably not required. The c string theory states that an array identifier without the bracket is the address of the first element of the characters. "a" is not defined in the program. it would probably give you a stack error. I would write it this way if(&a == a[]){printf("------"); this would only compare the address of the pointer to the address of the first element of the array.

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
0

C++ has an implicit conversion between an array reference and a pointer. This has been asked many times before, see for example this SO question.

Community
  • 1
  • 1
Gleno
  • 16,621
  • 12
  • 64
  • 85
0

In C, you can get away with comparing two different types of pointers, but your compiler should give you a warning.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132