Ankur Lathwal
Ankur Lathwal

Reputation: 725

is a==*a?? A query regarding pointers

int main()
{
int a[4][3] = {10,20,30,40,50,60,70,80,90,100,110,120};
printf("%d",((a==*a) && (*a==a[0])));
return 0;
}

Prints 1 on the console. Anyone has logical explanation??

Upvotes: 3

Views: 323

Answers (2)

haccks
haccks

Reputation: 106092

Arrays are converted to pointer when used in an expression except when they are an operand of sizeof and unary & operator. a and *a are of different types (after decay) but have the same address value.

  • a decays to pointer to first element (first row) of array and is of type int (*)[3].
  • *a dereference the row pointed by a and further decayed to pointer to first element of first row. It is of type int *.
  • a[0] is representing the first row which is of type int [3]. In expression it decays to pointer to first element of first row and is of type int * after decay.

As the address of an array the address of first byte, therefore address of an array, address of first row and address of first element all have the same value. So, after decay, all of a, *a and a[0] points to same location.

Here is a graphical view of the above explanation:

Stack Overflow What exactly is the array name in c?

Upvotes: 11

shashank
shashank

Reputation: 410

Is a==*a?


The answer is yes if the array a is multi dimensional array. 

so what if it is single dimensional? let me give you an example.
void main() { int a[4]={1,2,3,4}; printf("%d",((a==*a)&&(*a==a[0]))); }

  • The answer in this case would be 0.

  • This is because 'a' represent address of array or address of first element of array but *a represent value(pointer to that value). the address and value are different types so answer would be 0.

  • But in case of multi dimensional arrays 'a' represented as a[0][0] because it represent pointer to the first element of first sub array of multi dimensional array.
    So the answer is yes if the array is multi dimensional array

Upvotes: 0

Related Questions