3

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.

Shivam
  • 383
  • 1
  • 2
  • 8

2 Answers2

1

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;    
}
Steephen
  • 11,597
  • 6
  • 29
  • 41
1

An efficient solution would be to pass std::vector<Player> as a reference parameter. Clear it (in case it is already populated), call its reserve function to the number of incoming elements (if known) and use push_back or emplace_back to add new players one at a time. Although vectors may over-allocate a bit to increase performance of future allocations, I wouldn't worry about this. (Even if you moved to std::list which would only have as many nodes as players, it could still use more memory than vector as lists are not memory efficient).

This assumes your Player objects can be copied, as vectors sometimes need to copy elements internally. If not, then try std::vector<std::unique_ptr<Player>>. This is less efficient but doesn't require copying support on Player.

Neil Kirk
  • 20,002
  • 5
  • 48
  • 79