Search code examples
credefinition

Difference between redefinition of array elements in C


I am a beginner in C and During Programming I have found this code about bitwise addition

#define WORD_FROM_BUF(WRD) ((((unsigned char *)(WRD))[0]<<8)|((unsigned char *)(WRD))[1])

I have tried to modify this code to this form

 #define WORD_FROM_BUF(WRD) (((unsigned char *)(WRD[0])<<8)|((unsigned char *)(WRD[1]))

EDIT My problem is similar to these 2 questions C macros and use of arguments in parentheses- by Palec

Can we remove parentheses around arguments in C macros definitions?- by Palec

Thanks everyone for your explanations


Solution

  • (unsigned char *)(WRD) takes the pointer(?) WRD and converts it into a pointer to bytes. Indexing that byte-pointer with [0] gets the first byte from the buffer. When combining that with the next byte, you get a two-byte value.

    (unsigned char *)(WRD[0]) takes the first word(?) from the buffer and turns that word into a pointer. Totally different, and very likely totally wrong as shifting the pointer << 8 make little sense.

    Then WRD[1] picks up the second word from the buffer, not the second byte.