c - 获取指向字符串常量的指针

标签 c string pointers memory-management c89

short var = *((unsigned short*)&"BM");

"BM" 必须位于只读内存区域的某处,那么为什么我不能获得指向它的指针? (它编译但它说无效的内存区域(clang 编译器))

最佳答案

C 不允许获取文字的地址:

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

-- C99 6.5.3.2/1

文字不属于任何允许的操作数类别。这是语言的正式约束——符合规范的实现不需要接受违反它的代码,并且需要产生描述违规的诊断。 C 没有定义违反约束的代码的行为。

你可以像这样实现类似于你想要的东西:

union short_str {
    char str[3];
    int16_t sh;
} u = { "BM" };
short var = u.sh;

除其他外,这避免了取消引用指向未对齐存储的指针的风险。 C 将对齐变量 u 的存储,以便所有成员都在适当的边界上对齐。这避免了按照您最初尝试的路线使用任何方法时可能出现的陷阱。

关于c - 获取指向字符串常量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29673282/

相关文章:

c - C 套接字编程使服务器无法识别连接

r - 缩短 R 中的长向量

c - 如果检查指针值,指针/malloc() 会发生奇怪的崩溃

C 帮助 : Compiler gives me a "makes pointer from integer without cast" when using strlen()

相同地址的C结构分配有效吗?

c - 使用 SDCC (Little Endian) 编译器时这个算法有什么问题?

c - 没有 OpenCV 的开源 PSNR/SSIM C 实现?

c - 使用strtok解析C中的字符串并存储在数组中

c - 使用命令行参数将数据从第二个 txt 文件传输到第二个字符数组时遇到问题

ruby-on-rails - 如何从 Rails 中的字符串中识别一组日期