Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array index and address return same value

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

like image 474
n0nChun Avatar asked Sep 04 '10 12:09

n0nChun


Video Answer


1 Answers

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)

like image 109
Prasoon Saurav Avatar answered Oct 02 '22 15:10

Prasoon Saurav