Link to home
Start Free TrialLog in
Avatar of chsalvia
chsalvia

asked on

Reading integers from disk

When I read from disk I usually read into a void* type memory block, and then sort out the types using pointers.

But, I find strange discrepencies sometimes when dealing with integers.  For example, if I have a 64-bit integer stored in a void memory block, I access it by dereferencing the region in memory, and casting it to the appropriate type.

uint64_t number = (uint64_t) *( (byte*) membuffer + offset);

I also have to cast the void* pointer itself to a char*, or my byte* typedef, in order to add the offset distance.

I can also access the integer like this:

memcpy(&number, (byte*) membuffer + offset, sizeof(number));

The first method seems more direct, but it sometimes results in garbage numbers, whereas the second method always works properly.  Is there some reason that accessing the data via dereferencing the pointer and casting might not work properly?
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chsalvia
chsalvia

ASKER

That worked correctly, thanks.  But I'm confused.  Why would casting to a pointer-to-integer type, and then dereferencing that, result in something different than dereferncing a pointer and casting to an integer type?  It's the same memory region.
when you dereference a byte pointer, you get a byte.  when you dereference a uint64_t pointer, you get a uint64_t