c++ - 是否有可能有一个指针文字?

标签 c++ c pointers literals

在 C 中,可以有以下形式的字符串文字

char *string = "string here";

整数文字:

uint8_t num = 5;

长文字:

long long bigNum = 90322L; 

浮点字面量:

float decimal = 6.3f;

有一个指针字面量的方法吗?那是内存空间的文字地址。我正在做一些嵌入式项目的工作,需要硬编码 DMA 访问的值。我正在做类似于以下的事情:

uint32_t *source = 0x08000000;

虽然编译并正常工作,但我收到以下编译器错误(我使用的是 GCC 的变体):

cc0144: {D} warning: a value of type "int" cannot be used to initialize an entity of type "uint32_t *"
cc0152: {D} warning: conversion of nonzero integer to pointer

是否有正确的方法来执行此操作,还是我只需要接受它作为 C 的事实?我知道我能做到:

uint32_t *source = (uint32_t *)0x08000000;

但这似乎非常不必要。这样做的行业方法是什么?我也想知道 C++ 中是否存在此功能。

最佳答案

在 C 和 C++ 中,唯一的指针文字或常量是零。我们可以去draft C99 standard 6.3.2.3 指针部分:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55)

和:

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.56)

处理非零整数常量的正确方法是使用强制转换。

来自 draft C++ standard 的等效部分可能是 5.2.10 Reinterpret cast 部分说:

A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined. [ Note: Except as described in 3.7.4.3, the result of such a conversion will not be a safely-derived pointer value. —end note ]

您需要查看 3.7.4.3 部分以了解所有详细信息。

对于指针文字引用,您需要 2.14.7 Pointer literals 部分,其中说:

The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value. See 4.10 and 4.11. —end note ]

关于c++ - 是否有可能有一个指针文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24212792/

相关文章:

c++ - 如何从 C++ 调用 Delphi DLL WideString 参数(包括 var 参数)

c++ - 为什么不鼓励在堆上创建 std::string/std::map?

c++ - 如何创建像 WinAmp 这样的自定义皮肤

c - 传递 xxx 参数的指针目标的符号不同

c - 使用数组表示法访问函数内的三重指针

c++ - 是否可以引用随机类?

c++ - gcc c++ 命令行错误消息解析器

创建了一个函数来反转 C 中 double 数组的内容?但不工作

c - 我创建过程 Rand(a,b) 的方法的更好解决方案,使用过程 Rand(0,1)

c++ - 需要选择一个容器来存储我的数据