开发者

Dereferencing within a buffer

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 d开发者_开发问答oes not do what I'm expecting it to do. Can someone tell me the correct way to assign the value?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜