C++ 字符串字面量的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1392200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:50:06  来源:igfitidea点击:

Sizeof string literal

c++stringsizeof

提问by CsTamas

The following code

以下代码

#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;
}

outputs

产出

sizeof(string literal) = 2
sizeof(const char* const) = 4
sizeof(const char[]) = 2

on a 32bit OS, compiled with GCC.

在 32 位操作系统上,使用 GCC 编译。

  1. Why does sizeofcalculate the length of (the space needed for) the string literal ?
  2. Does the string literal have a different type (from char* or char[]) when given to sizeof?
  1. 为什么要sizeof计算字符串文字(所需空间)的长度?
  2. 字符串文字是否具有不同的类型(来自 char* 或 char[])sizeof

回答by Jonathan Leffler

  1. sizeof("f")must return 2, one for the 'f' and one for the terminating '\0'.
  2. sizeof(foo)returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointer.
  3. sizeof(bar)returns 2 because bar is an array of two characters, the 'b' and the terminating '\0'.
  1. sizeof("f")必须返回 2,一个用于 'f',一个用于终止 '\0'。
  2. sizeof(foo)在 32 位机器上返回 4,在 64 位机器上返回 8,因为 foo 是一个指针。
  3. sizeof(bar)返回 2,因为 bar 是一个包含两个字符的数组,即 'b' 和终止的 '\0'。

The string literal has the type 'array of size N of const char' where N includes the terminal null.

字符串文字的类型为“大小为 N 的数组const char”,其中 N 包括终端空值。

Remember, arrays do not decay to pointers when passed to sizeof.

请记住,数组在传递给 时不会衰减为指针sizeof

回答by Michael Foukarakis

sizeofreturns the size in bytes of its operand. That should answer question number 1. ;) Also, a string literal is of type "array to n const char" when passed to sizeof.

sizeof返回其操作数的字节大小。这应该回答问题 1。;) 此外,当传递给sizeof.

Your test cases, one by one:

您的测试用例,一一:

  • "f"is a string literal consisting of two characters, the character fand the terminating NUL.
  • foois a pointer (edit: regardless of qualifiers), and pointers seem to be 4 bytes long on your system..
  • For barthe case is the same as "f".
  • "f"是一个字符串文字,由两个字符组成,字符f和终止的 NUL。
  • foo是一个指针(编辑:不管限定符),并且指针在您的系统上似乎是 4 个字节长..
  • 对于bar这种情况与"f".

Hope that helps.

希望有帮助。