Search code examples
cpointerscastingdereference

what pointer magic is this


I am learning C. I am starting to understand pointers and type casting. I am following along with some guides and examples and I ran across this declaration:

uint32_t *sp;
...
*(uint32_t*)sp = (uint32_t)somevalue;

What is happening here? The first asterisk specifically is a mystery to me.


Solution

  • Breaking it down:

    *(uint32_t*)sp 
    

    basically says to treat sp as a pointer to uint32_t ((uint32_t *) is a cast expression), and to dereference the result.

    So,

    *(uint32_t*)sp = (uint32_t)somevalue;
    

    means, "take somevalue, convert it to type uint32_t, and store the result to the thing sp points to, and treat that thing as though it were also a uint32_t."

    Note that the cast on sp is redundant; you've already declared it as a pointer to uint32_t, so that assignment could be written as

    *sp = (uint32_t) somevalue;