Is dynamic memory only used for arrays? I understand that if you don't have a fixed size for your array, this is to be used. But does it have any other functions, i.e. just variables?
Thanks..
Is dynamic memory only used for arrays? I understand that if you don't have a fixed size for your array, this is to be used. But does it have any other functions, i.e. just variables?
Thanks..
Yes! If the memory you're trying to use is large (or a lot of it), then you use dynamic memory since the stack is limited to about 1 MB (or less on embedded systems), but the heap is limited to 2 GB (on Windows; may vary on other platforms, max 4 GB for 32-bit systems).
So, is that a yes, it is only used for arrays or yes, it can also be used in variables?Yes! If the memory you're trying to use is large (or a lot of it), then you use dynamic memory since the stack is limited to about 1 MB (or less on embedded systems), but the heap is limited to 2 GB (on Windows; may vary on other platforms, max 4 GB for 32-bit systems).
Thanks, Elysia..
As I explained, if the memory you need is very big, then you use dynamic memory. Dynamic memory is not limited to arrays, it can be used for any type of variables.
Dynamic memory is also used when you need to create memory that outlives the length of a function or when you dynamically need to create a variable or object.
I am just starting to read about dynamic memory and still familiarizing myself with the facts. Thanks, Elysia..
maybe the hardest thing about dynamic memory is that you have to keep track of the pointers so you would have "memory leak". That's why "large" program projects use profilers
"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg."-Bjarne Stroustrup
Nearing the end of finishing my 2D card game! I have to work on its 'manifesto' though <_<
Uhh no, profilers don't catch memory leaks (well, some might, but that is not the purpose of a profiler). They catch parts that needs to be optimized.
Dynamic memory isn't hard at all. You just need smart pointers. Classes that delete memory when no longer in use. C++ is so powerful, yet so underutilized by many.
You might also use dynamic memory when the lifetime of the variable you are creating needs to be longer than the function you create it in. One example is a Factory function that creates a variable of the correct kind of type depending on some input it gets. The function cannot create a local variable because that will die when the function ends, so it will create an instance using dynamic memory that will continue to exist when the function ends.
The new & delete operators have single object & array of object versions, so you can use it for 1 object or for x objects. Ex.
Code:int* pInt = new int; // Allocate 1 new int. char* str = new char[256]; // Allocate an array of 256 new chars. delete pInt; // Delete the single int. delete [] str; // Delete the array of chars.