-2

I need to understand the compilation error.

int main(int argc, char *argv[])
{

  int yocto[] = {100, 200, 300, 400};
  
  int *android = &yocto; // Getting error cannot convert ‘int (*)[4]’ to ‘int*’ in initialization

  int *linux = yocto; // Working fine.

  // But when I am printing the value of &yocto and yocto giving same address.

  cout<<"Value of &yocto : " <<&yocto<<endl; // 0x7ffc5f553e50

  cout<<"Value of yocto  : "<<yocto<<endl;  // 0x7ffc5f553e50

  return 0;

}  

Please explain me what is compiler internally doing with &yocto address.

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29
  • Imagine a pointer like a laser pointer. You can point to `int`s, to arrays, to structs, etc, etc, etc ... **but!** pointers to `int` are (let's say) red, pointers to arrays of 4 ints are green, .., ..., .... Now figure the array `{ 1, 2, 3, 4 }` and a green pointer pointing to the array and at the same time a red pointer pointing to the first element of the array. Do the pointers point to the same place? :-) – pmg Mar 12 '21 at 18:29
  • Rephrased, "Why can `int[4]` decay to `int*`, but `int(*)[4]` cannot?" There may be a duplicate. It should be clarified that both lines attempt to convert from one type to another. – Drew Dormann Mar 12 '21 at 18:31
  • Your `int *android = &yocto;` should be `int *android = &yocto[0];` Otherwise you are assigning the address of an array to the address of an integer. Arrays are not integers. – Thomas Matthews Mar 12 '21 at 18:32

1 Answers1

0

yocto is an array, but when used as an argument to assign to a pointer, it will decay into a pointer to the first element of the array. &yocto is a pointer to an array. Specifically, to a pointer to an int array of 4 elements, as that is what yocto is, so &yocto as the type of int (*)[4]

Christian Gibbons
  • 4,272
  • 1
  • 16
  • 29
  • Still i am confused with the answer, If we print the address of &yocto , yocto both address are same. cout<<"Value of &yocto : " <<&yocto< – Mukesh Kumar Mar 13 '21 at 12:47
  • The physical location is the same, but the type is different. Just like the address of the first member of a struct is the same as the address of a struct, but if you use the address-of operator (`&`) on them, they will be of different data-types. (At least this is true in C; not sure about C++ where structs are basically classes). – Christian Gibbons Mar 13 '21 at 17:33