What is the purpose of dynamically allocating a single element? In other words, when would someone ever use new instead of new[]?
I understand that new[] can be used to allocate a variable amount of memory, but new seems pointless to me. Why would you dynamically allocate a single element when you could just as easily declare a normal variable?
Many who have started learning about pointers would have a similar question...=)
Local variables are on the stack, and they don't persist - they are destroyed when a function returns. The programmer doesn't have to worry about the memory space allocated, although it makes it hard for functions to create objects that will in turn used by other functions(whatever media...) without making a copy from the stack.
The keyword new assigns memory spaces on the free store (the heap) and things stored in the spaces do persisit, until the program ends, or you explicitly state you're going to free that memory space when you're done with it. This can be very convenient as you can now pass the data to which the pointer is pointing (or the pointer itself) to functions that would make changes on the data.
new and new[] allocates memory on the heap, not on the stack.
Consequences:
1: it doesn't get deallocated at scope exit.
2: although you have to deallocate it with delete, delete[] manually
3: it's not uses stack space => anything big should be allocated with new or new[]
If you want to use new and new[] , I recommend to use boost::scoped_ptr, boost::scoped_array, boost::shared_ptr, boost::shared_array,
they automatically deallocate memory for you, even if an exception is thrown.
I thought new is used when we want to allocate space for single object, and new[] when we want to allocate memory for an array for example. Am I right ?