对 fstream 和指针感到困惑
我想编写一个函数,它接受一个 fstream,处理它,并在我在第二个参数中提供的 struct 中填充信息。
我的问题是,当我收到调试错误时,我很困惑如何使用指针和 fstream:
访问冲突写入位置 0xcccccccc。
这是主要函数:
int main()
{
keyframe_struct kfstruct;
string ifile = "filename";
ifstream fin( ifile, ios::binary );
load_from_keyframe_file( fin, kfstruct );
fin.close();
cout << kfstruct.num_keyframes << endl;
return 0;
}
这是我尝试用来解析二进制文件并在 struct kfstruct 中填充信息的函数:
struct keyframe_struct
{
int num_views;
int num_keyframes;
vector<keyframe> keyframes;
};
int load_from_keyframe_file( ifstream &fin, keyframe_struct &kfstruct )
{
char keyword[100];
while ( !fin.eof() )
{
fin.getline( keyword, 100, 0 );
if ( strcmp( keyword, "views" ) == 0 )
{
fin.read(( char* ) kfstruct.num_views, sizeof( int ) );
}
else if ( strcmp( keyword, "keyframes" ) == 0 )
{
fin.read(( char* ) kfstruct.num_keyframes, sizeof( int ) );
}
}
}
你能告诉我我做错了什么吗?我确信我在这里犯了一些巨大的错误,因为我只是一个初学者,我仍然不清楚我应该对指针做什么和不应该做什么。
I would like to write a function which takes an fstream
, processes it, and fills information in a struct
I supply in the second argument.
My problem is that I am confused how to use pointers and fstreams as I get debug errors:
Access violation writing location
0xcccccccc.
Here is the main function:
int main()
{
keyframe_struct kfstruct;
string ifile = "filename";
ifstream fin( ifile, ios::binary );
load_from_keyframe_file( fin, kfstruct );
fin.close();
cout << kfstruct.num_keyframes << endl;
return 0;
}
And here is the function I try to use for parsing the binary file and filling in the information in the struct kfstruct:
struct keyframe_struct
{
int num_views;
int num_keyframes;
vector<keyframe> keyframes;
};
int load_from_keyframe_file( ifstream &fin, keyframe_struct &kfstruct )
{
char keyword[100];
while ( !fin.eof() )
{
fin.getline( keyword, 100, 0 );
if ( strcmp( keyword, "views" ) == 0 )
{
fin.read(( char* ) kfstruct.num_views, sizeof( int ) );
}
else if ( strcmp( keyword, "keyframes" ) == 0 )
{
fin.read(( char* ) kfstruct.num_keyframes, sizeof( int ) );
}
}
}
Can you tell me what am I doing wrong? I'm sure I am making some huge errors here as I am just a beginner and I still don't understand clearly what should I and what should I not do with pointers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您忘记获取字段的地址:
[顺便说一句,请注意,从维护的角度来看,最好执行
sizeof(kfstruct.num_views)
。因此,如果类型发生变化,您的代码仍然可以工作。]You forgot to take the address of your fields:
[As an aside, note that it's better from a maintenance point of view to do
sizeof(kfstruct.num_views)
. So if the type ever changes, your code will still work.]而不是
的使用
在其他地方类似
。否则,您正在写入的地址等于您的 int 的 VALUE 的位置。你不想要这样。您希望将地址转换为
char*
。您可以通过“&”获取地址操作员。Instead of
use
similarly in the other place.
otherwise you are writing to a location whose address is equal to the VALUE of your int. You don't want that. You want the address converted to
char*
. You take the address by '&' operator.