So, I'm trying to send a pointer vector to a function, where I add some new members to it with the .pushBack() function. This works when I want only one member on the vector. But if I try to push more it throws a :
**terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc**
I've tried several things, this is my last attempt where I use a void ptr and a static cast to the vector, because I read that using the & creates a temporary address and so I've tried a more permanent one.
So, here it goes:
void humans(std::vector<Character> *human, unsigned human_count) {
for (unsigned i = 0; i < human_count; i++) {
unsigned human_x;
unsigned human_y;
unsigned human_id;
std::cin >> human_id >> human_x >> human_y; std::cin.ignore();
human->push_back(Human(human_id, Coordinates(human_y, human_x)));
}
}
int main()
{
unsigned x;
unsigned y;
Ash Pete;
std::vector<Character> human;
void *ptr;
Character *zombie;
unsigned human_count;
unsigned zombie_count;
ptr = &human;
while (1) {
std::cin >> x >> y; std::cin.ignore();
Pete.setPosition(Coordinates(y, x));
std::cin >> human_count; std::cin.ignore();
std::cerr << "HUMANS " << human_count << std::endl;
humans((static_cast<std::vector<Character>*>(ptr)), human_count);
std::cin >> zombie_count; std::cin.ignore();
zombies(&zombie, zombie_count);
human[0].print();
human[1].print();
if (human[1].getId() == 1)
std::cout << human[1].getPosition() << std::endl;
else
std::cout << human[0].getPosition() << std::endl;
}
}
It throws the error on the humans function. Thank you!