c++ - 指向文字的指针?

标签 c++ pointers literals

在阅读C++ Primer时,我遇到了这一行:
const char *cp = "Hello World";

据我了解,“Hello World”是一个字符串文字,它是一个常量字符数组。由于数组会衰减为指向数组中第一个元素的指针。这是否意味着 cp 指向 H 这是一个文字?是不是不可能有一个指向文字的指针,因为指针必须指向内存中对象的地址?

最佳答案

文字类型:boolean、integer、floating、character 和 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++ - 指向文字的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120047/

相关文章:

C++ - 文件读取中缺少行尾字符

C语言在另一个函数中接收struct

ruby 变量作为同一对象(指针?)

c - 无法从被调用函数返回更新后的字符串并释放内存

java - 将整数文字分配给Java中的 double 变量

python - 作为对象输入 python 3

c++ - SDL2 不接收窗口事件

c++ - 创建大量对象 C++

struct - 如何定义嵌入/匿名字段(go struct )

c++ - fstream 写入文件