在C ++中将数据写入内存 [英] Writing data to memory in C++

查看:270
本文介绍了在C ++中将数据写入内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在void * data中写一个int,char,real的混合。
我使用一个文件指针来运行数据块。
现在我的问题是,因为数据类型是void,我必须将其类型转换为int而写入整数和字符串的char。
虽然typecasting我使用下面的示例代码:

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.

推荐答案

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

到第4个整数(即,给定int size = 4的第16个字节),而不是第4个字节。也就是说,你的代码覆盖字节0-3,然后16-19,然后8th,然后9th。你可能的意思是: *(int *)((char *)data + X)

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 )

这篇关于在C ++中将数据写入内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆