Jacob Denson
Jacob Denson

Reputation: 391

Derefencing a cast

What does *(uint16_t *)"200" return? From what I understand, the "200" refers to a pointer to a character array, so the pointer refers to the '2' character, which in then converted to an integer via ascii characters, but I don't understand what the final * character does.

Upvotes: 3

Views: 73

Answers (1)

James McNellis
James McNellis

Reputation: 355069

Break the complex expression into pieces:

char const* a = "200";
uint16_t*   b = (uint16_t*)a;
uint16_t    c = *b;

a is a pointer to the initial character of the string literal ('2').

When we obtain b via the cast, we say "pretend the pointed-to data is actually a uint16_t (or an array thereof).

When we dereference b to obtain c, we obtain "the uint16_t at address b."

So, it's reinterpreting the first two characters (two bytes, 16 bits) of the string literal ("20"), as a uint16_t.

Upvotes: 3

Related Questions