tags:

views:

63

answers:

1

Let's say I had a char pointer pointing to a buffer that contained these values (in hex):

12 34 56 78 00 00 80 00

I want to modify the last two bytes to a short value of 42. So I would think I would have to do something like this:

(short)*(pointer+6)=42;

The compiler doesn't complain but it does not do what I'm expecting it to do. Can someone tell me the correct way to assign the value?

+5  A: 

The cast to "short" is happening after the assignment. What you want is:

*(short*)(pointer+6) = 42;

By the way, beware of aliasing issues. In this case you're probably ok since chars are assumed to be able to alias anything (edit: I stand corrected; this example breaks strict aliasing unless this data's actual type is "short"). But in general you should be very wary of cases where you are casting one pointer type to another. Google "strict aliasing" for more info.

Josh Haberman
But if the byte ordering of a short isn't what the OP wants, this probably won't do what the OP intends.
msw
Not true. Char * can alias anything, but the converse is *not* true: casting from char * to short * violates strict aliasing.
I suppose endianness is not an issue here,likely the OP wants just to be able to reread that short value on the same machine as "number 42".
ShinTakezou