gpt4 book ai didi

c++ - 从由相同代码创建的二进制文件读取时出现段错误

转载 作者:行者123 更新时间:2023-11-28 01:04:37 25 4
gpt4 key购买 nike

我已经编写了这段代码来生成 float 的二进制文件,但最后出现了段错误。它将 9000 个 float 写入文件,但在读取时只读取其中的 4096 个。当我运行可执行文件几次时,它读取的字节数在 4096、8192 和 9000 之间切换。但我总是有段错误...

float *realRef = new float [length];  //then filling it out...


ofstream out("blah.bin", ios::out | ios::binary);

out.write((char *) &realRef, length*sizeof(float)); //length is 9000
out.close();

ifstream in("blah.bin", ios::in | ios::binary);

float *readTest= new float[length];

in.seekg(0, ios::end);
size_t size=in.tellg(); // printing size shows 4096 BUT it should be 9000
in.seekg(0, ios::beg);

in.read((char *) &readTest, size);
cout << in.gcount() << " bytes read." << endl;

in.close();

最佳答案

您的代码中有错误。不需要取指针的地址。

//out.write((char *) &realRef, length*sizeof(float));
out.write((char *) realRef, length*sizeof(float));

//in.read((char *) &readTest, size);
in.read((char *) readTest, size);

关于c++ - 从由相同代码创建的二进制文件读取时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6952645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com