+ 2

Pointers, dynamic memory

Hello, I don't really get that one : I understood a pointer is the adress, in hexadecimal, of some variable (which you get by typing &variable), and you can get that variable by typing : *variable. Is that right ? But now, what exactly is the "new" function for ? Is it to create a new storage room, which you can then use with a variable you create right after that ? In that case, couldn't you just create that variable at the beginning of your program ? Thanks for your help !

20th Apr 2017, 2:04 PM
Nico
4 Respuestas
+ 2
When declaring and assigning a pointer in the following way, the pointer variable is located in the stack: int a = 1; int* b = &a; When using the new keyword, memory will be allocated in the heap to contain the variable: int* a = new int(); The heap is a different memory which is slower than the stack (due to it being unordered like a heap of hay). The new function is usually used to allocate dynamic memory (e.g for an array the size of can be changed) because you cannot change the stack in runtime
20th Apr 2017, 2:10 PM
G4S
+ 1
Nico, that is correct. The reason we use dynamic is because it is more efficient than allocating memory from the beginning. Another important aspect of dynamic memory is also the delete function. when you have massive projects, memory may be a hot commodity, therefore efficient use of memory and variables may be a priority. Take for instance a static list and a dynamic list that will get edited, added to, removed, etc. you may not know how large initially the list needs to be (for static allocation). It could have 100 items or 10, either case would be a guess at initialization. Dynamic can add items to lists and if they need to be removed you run the delete function and free up that memory. If you have a static list of 100 items and remove 99 items, the memory allocated is still 100, you will just have a value in one slot, but the rest of the memory is still associated to that list. So dynamic helps because you can just create and release memory as needed. Does that help?
20th Apr 2017, 2:19 PM
Ethan
0
Wow, thank you so much! I didn't expect to get answers so quickly, but that's perfect, I think I got it now, how it works and why it is useful... Thanks!!
20th Apr 2017, 3:17 PM
Nico
0
Your welcome :)
20th Apr 2017, 3:18 PM
G4S