Thread: Need help for pointer referencing

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    11

    Question Need help for pointer referencing

    Code:
    #define BYTE(thing,offset) (*(((unsigned char*)&thing)+offset))
    #define WORD(thing)        (*((unsigned int*)&thing))
    The code above are two macros used to isolate a byte of a multi-byte thing. But I'm so confused about the pointer reference and dereference process, and what's the point for using such macro? Can anyone explain to me and make a real example to demonstrate its purpose?

    All I can guess base on my knowledge is that:
    Code:
    unsigned int b = 9, a;
    a = WORD(b); // a = 9
    Thanks.

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    The * (dereference) operator works by looking at the type of the object you apply it to. If you apply it to a pointer to int, for example, the compiler knows to retrieve an int-sized object from whatever address the pointer contains.

    Thus these macros can take any type as an argument (any expression to which the & operator can be applied, to be exact), and pull out a particular number of bytes. It doesn't matter what type the expression has: the cast converts it to a known type which is then dereferenced. BYTE() always pulls out a single byte, while WORD() pulls out something the size of an unsigned int.

    BYTE() is perfectly portable: you can always use an unsigned char pointer to extract the bytes of an object. WORD() is not portable. Converting a random pointer type to unsigned int* might not be valid: you could, for example, convert a misaligned type, or a type that's too small. You also have endian issues to deal with.

    One use of WORD() would be to, say, read a file into an array of unsigned char; you know that at some offset in the file there's an unsigned int, so you use WORD() to extract it. This is terribly non-portable (the size of unsigned int can be different on different systems, plus the issues mentioned above).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Windows form C++ - referencing the form
    By rocketman50 in forum Windows Programming
    Replies: 2
    Last Post: 05-22-2010, 11:58 AM
  2. Symbol Referencing Error
    By Delpheno in forum C++ Programming
    Replies: 3
    Last Post: 01-31-2008, 09:03 PM
  3. Symbol referencing errors
    By n00pster in forum C++ Programming
    Replies: 9
    Last Post: 04-30-2007, 06:40 AM
  4. STL list and referencing
    By gautamn in forum C++ Programming
    Replies: 1
    Last Post: 06-13-2005, 12:40 AM
  5. referencing structure variables
    By sballew in forum C Programming
    Replies: 1
    Last Post: 11-01-2001, 01:56 PM