Search code examples
pointersreferencedereference

dereferencing a created pointer


I just have a quick question about what this code mean. Sorry, been reading other posts but I couldn't fully grasp the concept since none seems to resemble this piece of code that I'm currently working in my embedded system.

int8u buf[1024];
memset(buf, 0, sizeof(buf));
*((int16u*)&buf[2]) = 0xbb01;

can someone explain to me what these lines mean?


Solution

  • It basically interprets the array of bytes buf as 16-bit words and then changes the second word to 0xbb01. Alternative representation:

    int8u buf[1024];
    memset(buf, 0, sizeof(buf));
    
    int16u *words = buf;
    buf[1] = 0xbb01;
    

    &buf[2] takes the address to the second byte in buf. Then the cast to (int16u *) informs the compiler that the result is to be treated as a 16-bit unsigned integer. Finally, the memory on that address is set to 0xbb01.

    Depending on the endianness of your system, the contents of buf could then be 0x00, 0x00, 0xbb, 0x01 or 0x00, 0x00, 0x01, 0xbb (followed by more NULs due to the memset()).