Where does const char* get the pointer to a memory address?
why does a const char don't need a memory address to point to?*
It does.
A C-string literal like
"Anthony"
is decayed to the address of its 1st character. Like, BTW; any array in C does.
It does need a memory address, and it HAS a memory address. In your example it's simply the memory address of the beginning of the string. It's the same with any other array variable that's initialized at compile time, for instance "int array [] = {0, 1, 2, 3};".
If you used a binary editor to look at the executable, you would see the string "Anthony" in there. If you put the line "printf ("a is at %p\n", (void *)a);" in your program, then compile & run it, you'll see the address.
You can imagine this declaration
const char* a = "Anthony";
the following way
const char string_literal[] = "Anthony";
const char *a = string_literal;
That is the compiler creates an array of characters with the static storage duration that stores the string "Anthony"
and the address of the first character of the array (due to the implicit conversion of array designators to pointers to their first characters) is assigned to the pointer a
.
Here is a demonstrative program that shows that string literals are character arrays.
#include <iostream>
#include <type_traits>
decltype( auto ) f()
{
return ( "Anthony" );
}
template <size_t N>
void g( const char ( &s )[N] )
{
std::cout << s << '\n';
}
int main()
{
decltype( auto ) r = f();
std::cout << "The size of the referenced array is "
<< std::extent<std::remove_reference<decltype( r )>::type>::value
<< '\n';
g( r );
return 0;
}
The program output is
The size of the referenced array is 8
Anthony
The size of the string literal (of the array that stores the string literal) is equal to 8
because the string includes also the terminating zero character '\0'
.
In the demonstrative program the expression
std::extent<std::remove_reference<decltype( r )>::type>::value
may be substituted for just the expression
sizeof( r )