Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Allocate memory for objects read from file in a function and data accessible throughout program

How to create unknown no of objects at run time in C++, I am reading data from a text file and don't want to waste any memory i.e No extra objects and this has to be done in a function.

Player* g_data()
{
    system("cls");
    char name[40];int level;
    fstream file;
    file.open("data.txt",ios::app|ios::in|ios::out);
    Player data[40],*ptr[100];
    int i=0;
    while(!file.eof()&&i<100)
    {
        file >>name>>level;
        strcpy(data[i].name,name);
        data[i].level=level;
        data[i].id=i;
        ptr[i]=&data[i];
        cout<<"Address-"<<ptr[i]<<"data"<<ptr[i]->name<<"id"<<ptr[i]->id<<endl;
        i++;
    }
    system("pause");
    return ptr[i-1];    
}

The thing is I need access to the memory location after I return the object and I don't want that memory to fade away(as is the case with stack memory), Now how can I allocate memory and access the memory throughout the program without wasting any.

like image 384
Shivam Avatar asked Sep 10 '26 06:09

Shivam


1 Answers

Create a variable of std::vector<Player> inside function and insert into that, so you can keep any number of player objects pointers in it. You can return at end of the function.

std:vector<Player> g_data()
{
    system("cls");
    char name[40];int level;
    fstream file;
    std:vector<Player*> Players;
    Player data[40];
    int i=0;
    while(file.open("data.txt",ios::app|ios::in|ios::out))
    {
        if ( i ==100)
            break;
        file >>name>>level;
        strcpy(data[i].name,name);
        data[i].level=level;
        data[i].id=i;
        Players.push_back(data);
        cout<<"Address-"<<ptr[i]<<"data"<<ptr[i]->name<<"id"<<ptr[i]->id<<endl;
        i++;
    }
    system("pause");
    return players;    
}
like image 200
Steephen Avatar answered Sep 11 '26 19:09

Steephen