c - Weird error when using fread with struct -


so, trying read bmp image using fread , structs. create following struct read header

struct head{ char sigbm[2];//this 'b' , 'm' chars int filesize; int reserved; int offset ... }; 

and in main function used

fread(pointertostruct,sizeof(struct head),1,image); 

and got weird results. decided take char sigbm[2] struct , read different fread. like:

char sigbm[2]; struct head *p = malloc(sizeof(struct head));/* without char sigbm[2] */ fread(sigbm,sizeof(char),2,image); fread(p,sizeof(struct head),1,image); 

and worked!

i got working, want know why worked that

your data seem written disk without padding. is; integer filesize comes directly after 2 chars. not how structs kept in memory.

the size of

struct head{   char sigbm[2];//this 'b' , 'm' chars   // 2 padding bytes hide here   int filesize; } 

is 8 on machine. not 2+4 may expect. if read/write same compiler options on same platform can expect struct read in correctly. if not, need in control of details these.

most architectures require (or prefer) numeric types start @ specific multipliers of 2 [for example size of type itself].


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -