Array and pointers in c++ trying to understand the meaning of address of an array

163 Views Asked by At

I am trying to get a grasp of the meaning of the address of an array.

I wrote the following code to try to understand the meaning, but I could not grasp it:

char d [] {"Ashish"};

std::cout << d <<std::endl;

std::cout <<&d <<std::endl;

std::cout <<&d[0] <<std::endl;

std::cout <<(void*)&d[0] <<std::endl;

What will the output be for each statement? Why is the output for the 2nd and 4th statements the same?

1

There are 1 best solutions below

0
Ted Lyngmo On

std::cout << d <<std::endl;

Here the array decays into a pointer (a char*) to its first element. Since there is an operator<< overload taking a const char* in order to be able to print C strings, the string Ashish is printed.

std::cout << &d <<std::endl;

Here you take the address of the array to form a pointer to a char[7]. There is no specific operator<< overload for that but there is a fallback overload for void* which will be used to print the address.

std::cout << &d[0] <<std::endl;

Here you form a pointer to the first element in the array. Again, this is a char* and the same operator<< as in the first case will be used.

std::cout << (void*)&d[0] <<std::endl;

Here you form a pointer to the first element in the array but cast it to void* so the operator<< overload used in the second case will be used here too.