i dunno where is the problem exactly, but it seems when i pass ‘Memory’ by reference, it doesn’t work. im trying to Read a Word From Memory in Big Endian and Increment Data by 2
here is how i do it
WORD ReadBigEndianWORD(char **Data)
{
WORD Result = (unsigned char) *Data[0];
Result <<= 8;
Result |= (unsigned char) *Data[1];
*Data++
return Result;
}
and i call it like this
char *Memory = ........;
WORD MyWord = ReadBigEndianWORD(&Memory);
the code above doesn’t work (works if Function Argment is ‘char *Data’ and Data passed as ‘Memory’);
and is this the best way to read Big Endian from Memory?
thanks;
Your code is failing because of the operation precedence of the
*operator and the[]operation. The[]has higher precedence, so you need to change your code to:The line with
*Data[0]ends up working correctly because you’re adding an offset of zero. The second*Data[1]will either crash our give you bad data because it’s reading for uninitialized memory.*Data[1]is equivalent to\*(\*(Data + sizeof(char**))), so it’s tacking the the location where Memory is stored and moving past that.The best way to see what’s happening is to use your original
ReadBigEndianWORDand change the calling code to:If you do that you’ll see that *Data[1] is pointing to Memory[1].
And then to move your Data pointer to the next work you need to increment it by the sizeof a
WORD, not the size ofchar**which is what++will do.But as everyone else has said you should change your method to take a
char*and then worry about moving around in your buffer in the calling code. That will make your function cleaner and clearer.