views:

129

answers:

2
#include<stdio.h>
int main(void) {
  int a[3] = {1,2,3};
  printf("\n\t %u %u %u \t\n",a,&a,&a+1);
  return 0;
}

Now i don't get why a and &a return the same value, what is the reasoning and the practical application behind it? Also what is the type of &a and could i also do &(&a) ?

+10  A: 

Now i don't get why a and &a return the same value, what is the reasoning

a is the name of the array that decays to pointer to the first element of the array. &a is nothing but the address of the array itself, although a and &a print the same value their types are different.

Also what is the type of &a?

Pointer to an array containing three ints , i.e int (*)[3]

could i also do &(&a) ?

No, address of operator requires its operand to be an lvalue. An array name is a non-modifiable lvalue so &a is legal but &(&a) is not.

Printing type of &a(C++ Only)

#include <typeinfo>
#include <iostream>

int main()
{
   int a[]={1,2,3};
   std::cout<< typeid(&a).name();
}

P.S:

Use %p format specifier for printing address(using incorrect format specifier in printf invokes Undefined Behavior)

Prasoon Saurav
n0nChun
@n0nChun : Edited my post. :)
Prasoon Saurav
Yeah, but why would i use c++ to tell me the type if i am working on C. Isn't there any other reason why the type is int (*)[3]? Or is it something that just makes sense, thinking about it logically?
n0nChun
@n0nChun : For an array of n elements of type `T`, the address of the first element has type `‘pointer to T’`; the address of the whole array has type `‘pointer to array of n elements of type T’`.
Prasoon Saurav
Thanks. And i found this too : )http://publications.gbdirect.co.uk/c_book/chapter5/arrays_and_address_of.html
n0nChun
@n0nChun: If you say `int i;` you did not declare `i` as a pointer to `int`, yet `)
FredOverflow
i have to ask one more thing.if you say int a[3]={1,3,4};int *p;p =
n0nChun
fahad
A: 

a is the base address of the array. When you use &a it gives the the address of the address of a..Suppose the address of a is ff01 then it will become &a==&(ff01) and finally it will give you the address where the contents are ff01 and same goes for &&a.

fahad