Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Writing data to memory in C++

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

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

1 Reply

0 votes
by (71.8m points)
*((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 )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...