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();
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.