char* 是否用作内存中字节的位置?
Is char* used as the location of a byte in memory?
我知道这段代码的作用:将 &x 指向的内存中的内容复制到文件中,大小为 sizeof(double) 字节;读取文件并复制到 &y 指向的内存中,为 sizeof(double) 字节。
double x,y;
std::ofstream out( "abc.dat", std::ios::out | std::ios::binary);
out.write( reinterpret_cast<const char*>(&x), sizeof(double));
out.close();
std::ifstream in( "abc.dat", std::ios::in | std::ios::binary);
in.read( reinterpret_cast<char*>(&y), sizeof(double));
in.close();
据我了解,在进行二进制IO时,文件和RAM之间的数据流动应该以字节为单位。然后 &x 地址应该作为字节位置传递:像 out.write( reinterpret_cast< const byte*>(&x), sizeof(double)) 这样的东西是有意义的。但是C++没有定义字节类型,这里的char*可以理解为字节位置,对吧?我注意到 char 的大小与一个字节相同,它们都是 8 位。
是的,在 C++ 中 char 的大小是 1 个字节。
除此之外,尺寸更加流畅。这就是为什么一些供应商提供非标准扩展以保证大小的原因。例如在 Microsoft VC 中有 16 位的 WORD。
查看此页面了解更多信息:http://en.cppreference.com/w/cpp/language/types
我知道这段代码的作用:将 &x 指向的内存中的内容复制到文件中,大小为 sizeof(double) 字节;读取文件并复制到 &y 指向的内存中,为 sizeof(double) 字节。
double x,y;
std::ofstream out( "abc.dat", std::ios::out | std::ios::binary);
out.write( reinterpret_cast<const char*>(&x), sizeof(double));
out.close();
std::ifstream in( "abc.dat", std::ios::in | std::ios::binary);
in.read( reinterpret_cast<char*>(&y), sizeof(double));
in.close();
据我了解,在进行二进制IO时,文件和RAM之间的数据流动应该以字节为单位。然后 &x 地址应该作为字节位置传递:像 out.write( reinterpret_cast< const byte*>(&x), sizeof(double)) 这样的东西是有意义的。但是C++没有定义字节类型,这里的char*可以理解为字节位置,对吧?我注意到 char 的大小与一个字节相同,它们都是 8 位。
是的,在 C++ 中 char 的大小是 1 个字节。
除此之外,尺寸更加流畅。这就是为什么一些供应商提供非标准扩展以保证大小的原因。例如在 Microsoft VC 中有 16 位的 WORD。
查看此页面了解更多信息:http://en.cppreference.com/w/cpp/language/types