Search code examples
cstringpointersmemory-managementc89

Obtaining pointer to a string constant


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))


Solution

  • 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 the register 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.