【发布时间】:2014-03-26 09:57:12
【问题描述】:
程序中writeSector函数调用seekToSector。当 seekToSector 调用 seekp 时,writeSector 中的 sec 变量会发生变化。谁能解释原因或给出解决方案?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Sector
{
public:
int num;
char data[1020];
Sector()
{
num = -1;
for(int i=0;i<1020;i++)
data[i] = (char)0;
}
Sector(int n,string str)
{
num = n;
for(int i=0;i<str.length();i++)
data[i] = str[i];
}
string toData()
{
string str = to_string(num);
for(int i=0;i<1020;i++)
str += data[i];
return str;
}
};
class Disk
{
public:
fstream dskfl;
int currentPos;
void seekToSector(int index)
{
currentPos = index;
dskfl.seekp(1024*currentPos);
}
void writeSector(int index, Sector * sec)
{
seekToSector(index);
dskfl.write(sec->toData().c_str(),1024);
}
};
Sector * func()
{
Sector sec(0,"something");
return &sec;
}
void main()
{
Disk disk;
disk.dskfl.open("name",ios::binary | ios::out);
disk.writeSector(0,func());
}
【问题讨论】:
-
人们下载文件来查看您的代码的可能性很小。将其简化为展示行为的最小示例,或至少发布相关部分。
-
您几乎可以肯定在代码中的某处调用了未定义的行为。使用像 valgrind 这样的工具来找到它。
-
-1 表示“东西东西”。该规则的原因是为了防止低质量问题,其中包括代码转储和“我的代码没有工作,为什么”,您的问题肯定是其中之一。