-3

The C code is like this:

#include <stdio.h>
typedef unsigned char BYTE; 
int main(void) {
    unsigned int num, *p;
    p=&num;
    num=0;
    *(BYTE *)p=0xff;
}

But I do not understand the meaning inside the main function. Can anybody help?

2 Answers2

1
  1. num is an unsigned int
  2. p is a pointer to that same int.
  3. (BYTE*)p means "pretend its really a pointer to a byte instead".
  4. *(BYTE*)p = means "Go set that byte to be the value on the RHS."
  5. the value on the RHS is 0xFF.

Result: num is a 4-byte integer.
One byte of that int will be set to 0xFF
(it could be the high-byte or the low-byte depending on your platform)

So num will either end up being 0xFF 00 00 00, or possibly 0x00 00 00 FF

abelenky
  • 63,815
  • 23
  • 109
  • 159
0

The behaviour of the program is undefined.

(BYTE *)p is an invalid cast since the types are unrelated.

You cannot cast an unsigned int* to an unsigned char*. (For example, it's possible that these pointers occupy entirely different memory locations, and the C standard allows for that).

For more details, see C: When is casting between pointer types not undefined behavior?

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483