以下代码
#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
在 32 位操作系统上,使用 GCC 编译。
sizeof
为什么要计算字符串字面量(所需空间)的长度?- 当给
sizeof
时,字符串文字是否具有不同的类型(来自 char* 或 char[])?
最佳答案
sizeof("f")
必须返回 2,一个用于 'f',一个用于终止 '\0'。sizeof(foo)
在 32 位机器上返回 4,在 64 位机器上返回 8,因为 foo 是一个指针。sizeof(bar)
返回 2,因为 bar 是一个由两个字符组成的数组,即 'b' 和终止符 '\0'。
字符串字面量的类型为“const char
大小为 N 的数组”,其中 N 包括终端 null。
请记住,数组在传递给 sizeof
时不会衰减为指针。
关于c++ - Sizeof 字符串字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392200/