#Dynamically allocated memory
12 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.
A good example is probably related to user input.
E.g. the user can input a number of elements of some kind. Could be really anything. From the amount of players in a game or just other kind of data
As you don't know the size at the moment you compile your program you can just allocate the space at runtime
int PlayerAmount;
std::cout << "How many players are there: ";
std::cin >> PlayerAmount;
Player* players = new Player[PlayerAmount];
// do stuff and once you don't need them anymore you release the space you took
delete[] players;
But usually you would not write it like this as we already have tools provided by the C++ standard library.
That's a good case for std::vector<Player>. This does this work under the hood
Not a code example, but imagine you need a very large matrix in your code. if you don't define it using dynamic memory allocation, it will by default allocate memory on the stack - which is limited, so your code might segfault because the matrix is too large
in that case you need to allocate memory on the heap using dynamic memory allocation
like Yinsei mentioned, anything you don't know the size of at compile time should be dynamically allocated
[SOLVED] Dynamically allocated memory
Dynamically allocated memory