For a single integer, this makes sense if you need to save the value after, for example, after returning from a function. If you declared someInt , as you said, that would be invalidated as soon as it went beyond.
However, as a rule, it is more used for dynamic distribution. There are many things that your program does not know before distribution and depends on the input. For example, your program should read an image file. How big is this image file? We could say that we store it in such an array:
unsigned char data[1000000];
But this will only work if the image size is less than or equal to 1,000,000 bytes, and will also be wasteful for smaller images. Instead, we can dynamically allocate memory:
unsigned char* data = new unsigned char[file_size];
Here file_size defined at runtime. You could not say this value at compile time.
source share