+ 2
Pointer problem? [SOLVED]
Output's wonky here: https://code.sololearn.com/cAmf8B5A36vQ/?ref=app My best guesses have been implied types, negative values, misusing float pointers (too long), etc. Can anyone tell me why the pointer isn't doing what I want AND why the output's unstable at "byte" 2?
2 Answers
+ 2
@Anandkumar C B: Thanks. I wanted the bytes in the float. I understand from your response that (float + offset) indexes / depends on pointer type rather than a single-byte base.
I had tried casting fp to char* but apparently that's illegal (hoping for: warn + permit, so I could use the " printf(..., cp[i]) (char pointer)).
Using * and & it gets hacky, but this is clear:
union float_bytes {
float val;
unsigned char bytes[sizeof(float)];
} data;
data.val = fp*;
loop i: printf("%02X", data.bytes[i]);
This works. Thanks for the explanation.
+ 1
I don't know what you wanted from this program , but I can see pointer not being used correctly. firstly fp[0] = content pointed by fp + size of (float)*0... fp[1] = address pointed by fp + size of ( float)*1 .... fp[2] = address pointed by fp + size of (float)*2
so as you can see you are accessing out of boundary and might end up getting wrong value ... good that you were only reading that location the write would have resulted in segmentation fault . if you want I can correct this program and post it.