Possible Duplicate:
Differences between dynamic memory and “ordinary” memory
I was reading the C++ tutorial and I don’t understand why I need to declare dynamic memory, this is what the tutorial says:
Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program.
And then it says that we have to use new and delete operators to use dynamic memory.
However, I seem to be using dynamic memory when declare a pointer, e.g. char* p, for which I have not specified the length of the array of characters. In fact, I thought that when you use a pointer you are always using dynamic memory. Isn’t it true?
I just don’t see the difference between declaring a variable using new operator and not. I don’t really understand what dynamic memory is. Can anyone explain me this?
No it’s not true, for example
You need dynamic memory when you can’t tell how big the data structure needs to be.
Say you’ve to read some ints from a file and store them in memory. You have no idea how many ints you need. You could pick a figure of 100, but then your program breaks if there are 101. You could pick 100,000 hoping that’s enough, but it’s waste of resources if there’s only 10 in the file, and again, it breaks if there’s 100,001 ints in the file.
In this scenario your program could iterate through the file, count the number of ints, then dynamically create an array of the correct size. Then you pass over the file a second time reading the ints into your new array.
Static v’s Dynamic Memory
Static memory is static because once the program is compiled it can’t be changed, it is static. Variables you declare in functions, and members declared on classes / structs are static. The compiler calculates exactly how many of each its going to need as each method gets called.
Dynamic memory is a “pool” of memory that can be made available to your program on demand, at run time.
The compiler only knows it needs to allocate some (probably unknown) amount of that memory, and to release that memory back to the dynamic memory pool.
Hope this helps.
P.S. Yes, there are more efficient ways to get an unknown number of items into memory, but this is the simplest to explain