指向文字的指针?
Pointer to a literal?
在阅读 C++ Primer 时,我遇到了这一行:
const char *cp = "Hello World";
根据我的理解,"Hello World"
是一个字符串文字,它是一个常量字符数组。由于数组衰减到指向数组中第一个元素的指针。这是否意味着 cp
指向 H
这是一个文字?不是不可能有一个指向文字的指针吗,因为指针必须指向内存中对象的地址?
文字类型的存储类型:布尔型、整数、浮点型、字符和 nullptr 未指定,因此它们不需要在内存中有存储位置。
指定了文字串类型的存储类型:
"...字符串文字具有静态存储持续时间,因此在程序的整个生命周期中都存在于内存中..." 来源:https://en.cppreference.com/w/cpp/language/string_literal
因此可以获取文字字符串的地址并将其存储在 const char *
.
正如@MichaelKenzel 所建议的:
来自 C++17 标准草案 (n4659) https://timsong-cpp.github.io/cppwp/n4659/lex.string#16
Evaluating a string-literal results in a string literal object with
static storage duration, initialized from the given characters as
specified above. Whether all string literals are distinct (that is,
are stored in nonoverlapping objects) and whether successive
evaluations of a string-literal yield the same or a different object
is unspecified. [ Note: The effect of attempting to modify a string
literal is undefined. — end note ]
在阅读 C++ Primer 时,我遇到了这一行:
const char *cp = "Hello World";
根据我的理解,"Hello World"
是一个字符串文字,它是一个常量字符数组。由于数组衰减到指向数组中第一个元素的指针。这是否意味着 cp
指向 H
这是一个文字?不是不可能有一个指向文字的指针吗,因为指针必须指向内存中对象的地址?
文字类型的存储类型:布尔型、整数、浮点型、字符和 nullptr 未指定,因此它们不需要在内存中有存储位置。
指定了文字串类型的存储类型: "...字符串文字具有静态存储持续时间,因此在程序的整个生命周期中都存在于内存中..." 来源:https://en.cppreference.com/w/cpp/language/string_literal
因此可以获取文字字符串的地址并将其存储在 const char *
.
正如@MichaelKenzel 所建议的:
来自 C++17 标准草案 (n4659) https://timsong-cpp.github.io/cppwp/n4659/lex.string#16
Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. [ Note: The effect of attempting to modify a string literal is undefined. — end note ]