short var = *((unsigned short*)&"BM");
"BM"
must be located somewhere in read-only memory area then why can't I obtain a pointer to it? (It compiles but it says invalid memory area (clang compiler))
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
The type of a narrow string literal is an array of char , and the type of a wide string literal is an array of wchar_t . However, string literals (of both types) are notionally constant and should consequently be protected by const qualification.
In the pointers to constant, the data pointed by the pointer is constant and cannot be changed. Although, the pointer itself can change and points somewhere else (as the pointer itself is a variable).
The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.
C does not permit taking the address of a literal:
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
Literals do not fall into any of the permitted categories of operands. This is a formal constraint of the language -- conforming implementations are not required to accept code that violates it, and are required to produce diagnostics describing violations. C does not define the behavior of code that violates a constraint.
You can achieve something similar to what you seem to want like so:
union short_str {
char str[3];
int16_t sh;
} u = { "BM" };
short var = u.sh;
Among other things, this avoids the risk of dereferencing a pointer to misaligned storage. C will align the storage for variable u
so that all members are aligned on an appropriate boundary. This avoids a possible pitfall with any approach along the lines you originally attempted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With