This question already has an answer here:
when to use new in C++?
6 answers
I can't seem to understand the difference between using new to get more memory and just declaring a variable. here is where I read it in a book called jumping into C++:
Getting more memory with new
Dynamic allocation means requesting as much (or as little) memory as you need, while your program is running. You program will calculate the amount of memory it needs instead of working with a fixed set of variables with a particular size. This section will provide the foundation of how to allocate memory, and subsequent sections will explain how to fully take advantage of having dynamic allocation.
First let’s see how to get more memory. The keyword new is used to initialize pointers with memory from the free store. Remember that the free store is a chunk of unused memory that your program can request access to. Here's the basic syntax:
int *p_int = new int;
The new operator takes an "example" variable from which it computes the size of the memory requested. In this case, it takes an integer, and it returns enough memory to hold an integer value.
So what I don't understand is that how is: int *p_int = new int; any different to: int *p_int;
Aucun commentaire:
Enregistrer un commentaire