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?
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
when you dereference a byte pointer, you get a byte. when you dereference a uint64_t pointer, you get a uint64_t
ASKER