Imobilis
Imobilis

Reputation: 1489

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

Upvotes: 7

Views: 126

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

The simplest solution is of course:

short var= 0x424D;    // memory reads 4D, 42 = 'M', 'B'

or

short var= 0x4D42;    // memory reads 42, 4D = 'B', 'M'

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180161

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.

Upvotes: 5

Related Questions