Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to write a a mix of int, char, real in void *data. I am using a file pointer to run through the data block. Now my question is that since the data type is void, I have to typecast it to int while writing integer and char for writing string. While typecasting I used the following sample code:

*((int *)data+0) = 14;      //writing int
*((int *)data+4) = 5;       //writing int, left a space of 4 bytes for int
*((char *)data+8) = 'a';    //writing char
*((char *)data+9) = 'f';    //writing char

But then while reading the values back it didnt give the correct value.

cout<<*((int *)data+0);
cout<<*((int *)data+3);
cout<<*((char *)data+8);

Is the way my code is written correct? I am doubtful about it as data is void.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

*((int *)data+4) = 5; // writing 4th int
cout<<*((int *)data+3); // but reading third one

And just in case, ((int *)data+4) points to 4th integer (that is, 16th byte given int size = 4), not to 4th byte. That is, you code overwrites bytes 0-3, then 16-19, then 8th, then 9th. What you probably meant is: *(int *)( (char*)data + X )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...