Function in c++

Hello. I'm new to this forum so bear with me :D

I have a problem with the following program. So far, the only problem I have is when I try to separate it as functions. In other words, when the main() calls for a function and goes back to main, it doesn't recognize the variables that I created in the other function.


#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;

struct example{
char name[40];
int potions;
};



int structini()
{

struct example hero; //declares instance of struct type 'example' called 'hero'.
strcpy(hero.name, "Leroy Jheeenkins");
hero.potions = 5;
//write data

ofstream save_1("savefile", ios::out|ios::binary);
if(!save_1) //Couldn't open save file.
{
cout<< "Save failed."<<endl;
return 1;
}
save_1.write((char *) &hero, sizeof(struct example)); //writes entire struct to file.
save_1.close();

return 1;

}



int main()
{

structini();
//closes file stream

ifstream load_1("savefile", ios::in | ios::binary);
if(!load_1)
{
cout<< "Cannot load file"<<endl;

return 1;
}


load_1.read((char *) &hero, sizeof(struct example)); //loads the saved struct.
cout<<hero.name<<endl;
cout<<"Number of potions: " << hero.potions<<endl;
load_1.close();

system ("pause");

return 0;
}


///// end of program //////

The load_1.read is the one that gives me a problem. Thanks in advance.



hero is a local variable (on the stack). It vanishes when structini() returns.
If you want the caller on structini() to access it, you must dynamically allocate
it and return a pointer to it.
Topic archived. No new replies allowed.