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 theregister
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/