以下代码
#include <iostream>
using namespace std;
int main()
{
const char* const foo = "f";
const char bar[] = "b";
cout << "sizeof(string literal) = " << sizeof( "f" ) << endl;
cout << "sizeof(const char* const) = " << sizeof( foo ) << endl;
cout << "sizeof(const char[]) = " << sizeof( bar ) << endl;
}
输出
sizeof(string literal) = 2
sizeof(const char* const) = 4
sizeof(const char[]) = 2
在使用GCC编译的32位操作系统上。
sizeof
为什么会计算字符串字面量所需的空间(长度)?- 当字符串字面量被传递给
sizeof
时,它是否具有与char*
或char[]
不同的类型?
sizeof(const char *)
,无论该指针大小是多少,并且当然与字符串的实际长度无关。在某些平台/架构/编译器(历史上),指针大小和布局会根据类型而改变。这就是为什么,例如,在可变参数函数调用中,必须_显式地_将指针强制转换为其预期类型(如果它们不同),因为强制转换可能完全更改指针值。 - Qix - MONICA WAS MISTREATED