Dynamic Memory | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Dynamic Memory

Hey! Could you explain me what the " new " does, what dynamic memory allocation is and how it helps us?

4th Jan 2017, 12:29 PM
Konstantinos Kritharidis
Konstantinos Kritharidis - avatar
9 Answers
+ 7
This can help you "link" objects together so when the one changes, the other changes too.
4th Jan 2017, 1:15 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 4
Hello Konstantinos. You use new to instantiate an object in memory. I will try to explain using an example, ok? //Here you have a NEW person, named Peter. Person a = new Person(); a.name = "Peter"; //Here you have the SAME person, not a new one. Person b = a; //Here you have a NEW person. Person c = new Person(); c = a; //Now check it out. b.name = "Paul"; //If you print b.name, it will show "Paul". //If you print a.name, it will show "Paul" as well. //If you print c.name, it will show "Petter". //It happens because b is the same person on a, but c is a new one. c.name = "Stephen" //Now you have a.name as "Paul", b.name as "Paul" and c.name as "Stephen". I hope it helps. See ya.
4th Jan 2017, 1:02 PM
Guilherme Lima
Guilherme Lima - avatar
+ 3
new alocates memory on the heap to store data. It is memory that has to be manually handled unlike memory on the stack which is handled automatically by the compiler
4th Jan 2017, 1:05 PM
Jason Hoffman
Jason Hoffman - avatar
+ 3
what it means is most variables that you will use are handled automatically, there memory is allocated by the compiller when you give your variable a type ie float or int it reserves the nessesary amount of memory. For some programs you will have to reserve enough memory for an unknown data quantity this is where new comes in it can adjust its memory allocation to handle the amount of data coming in.
4th Jan 2017, 1:14 PM
Jason Hoffman
Jason Hoffman - avatar
+ 2
Every answer is welcome.
4th Jan 2017, 12:32 PM
Konstantinos Kritharidis
Konstantinos Kritharidis - avatar
+ 2
Anyone?
4th Jan 2017, 1:00 PM
Konstantinos Kritharidis
Konstantinos Kritharidis - avatar
+ 2
Thanks for the answer, but what does this mean for the programmers?
4th Jan 2017, 1:07 PM
Konstantinos Kritharidis
Konstantinos Kritharidis - avatar
+ 2
how does this help us?
4th Jan 2017, 1:12 PM
Konstantinos Kritharidis
Konstantinos Kritharidis - avatar
+ 2
Thanks :)
4th Jan 2017, 1:16 PM
Konstantinos Kritharidis
Konstantinos Kritharidis - avatar