开发者

Confused with fstream and pointers

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 ) );
        }

    }

}开发者_StackOverflow中文版

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.


You forgot to take the address of your fields:

fin.read(( char* ) &kfstruct.num_views, sizeof( int ) );
                  ^^^

[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.]


Instead of

( char* ) kfstruct.num_views

use

( char* ) (&kfstruct.num_views)

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜