#Dynamically allocated memory

12 messages · Page 1 of 1 (latest)

spare grotto
#

Can someone explain why dynamically allocated memory is useful and give a code example?

heady flumeBOT
#

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.

wise viper
#

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

modest saddle
#

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

spare grotto
#

Ah, I understand. Thank you guys !

#

!solved

heady flumeBOT
#

[SOLVED] Dynamically allocated memory

heady flumeBOT
#

Dynamically allocated memory