Suppose we define constchar *names[ ] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ;
In this declaration names[ ] is an array of pointers.
It contains base addresses of respective names.
That is, base address of “akshay” is stored in names[0],
base address of “parag” is stored in names[1] and so on.
Now, when we say cout<<names[0], why does it output "akshay" and not the address of akshay ?
Also why const char is used an not char ? What is the meaning of const in the above case?
Please can you explain me in a bit more detail through an example. The names : Akshay, etc. are located somewhere else in the memory. At names[0], it is the address that is stored. Then why does it output Akshay ? Please, if possible explain through an example of code ?
#include <iostream>
int main()
{
constchar* names[] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ;
constchar* a_name = names[0] ;
std::printf( "%s\n", a_name ) ; // print a_name as a null-terminated c-style string - prints the characters
std::cout << a_name << '\n' ; // same as above: type of 'pi' is 'pointer to const char'
// calls operator<< ( const char* ) - prints the characters
std::printf( "%p\n", a_name ) ; // print a_name as a 'pointer to void' - prints the address
std::cout << (constvoid*)a_name << '\n' ; // same as above: calls operator<< ( const void* ) - prints the address
constint n = 9 ;
constint* pi = &n ;
std::cout << pi << '\n' ; // type of 'pi' is not 'pointer to (const) char'
// calls operator<< ( const void* ) - prints the address
}
An element in your array is a constchar*. It should be clear why overload
resolution selects constchar* rather than void*.
The other example of JLBorges has a constint*. There is no exact match.
The compiler has three options:
1. implicit conversion from int* to void*
2. implicit conversion from int* to char*
3. report error