这可能是简单的问题
但是为什么const char *不需要指向内存地址?
示例:
const char* a = "Anthony";
不是
const char *a = // Address to const char
像其他类型一样吗?
为什么要使用const char不需要指向内存地址?*
是。
C字符串文字,如
"Anthony"
被衰减到其1 st字符的地址。就像,顺便说一句; C中的任何数组都可以。
您可以想象这个声明
const char* a = "Anthony";
以下方式
const char string_literal[] = "Anthony";
const char *a = string_literal;
即编译器将创建一个具有静态存储持续时间的字符数组,用于存储字符串"Anthony"
,并且该数组的第一个字符的地址已分配给指针a
。
这里是一个演示程序,它显示字符串文字是字符数组。
#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 size of the referenced array is 8
Anthony