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

Need example of Dynamic Memory

Hi everyone. I think I know what static memory is now, so can somebody please provide me on how to use Dynamic Memory? I kind of understand it and I've found tons of examples of simple code using Dynamic Memory but I can't understand what exactly is going on. I know it's for reserving memory from the heap but I don't know how to write code to use it. Basically, I would appreciate it if somebody could provide me an example of Dynamic Memory usage and explain everything for me including the 'new' and 'delete' operators, and then re-using the variable. Thanks!

30th Apr 2018, 3:48 AM
CheatingPenguin
7 Answers
+ 1
suppose you want to store 20 doubles double *names = new double [20] this allocates 20 * sizeof(double) memory into heap, which is big enough store these data and doesn't have fixed size. so in case, if the data is bigger than the memory of heap, then it will be allocated some extra memory whereas stack (where our normal variables are stored) has fixed size. so if you allocate some big data to stack, it will cause stack overflow to prevent this, 'new' is used but the thing with new is it stays there till you delete it, unlike normal variables which is thrown out as soon as its out of scope in short, using new you can create a global array of pointer which can be deleted any time in the program
30th Apr 2018, 5:09 AM
‎ ‏‏‎Anonymous Guy
0
Here I have code for memory allocation using calloc https://code.sololearn.com/czvJ1bM8DdhX/?ref=app [Edit:]well sorry I didn't noticed tag c++ this is code for c
30th Apr 2018, 4:26 AM
Yugabdh
Yugabdh - avatar
0
I modified code to run it on c++ now, hope it will help https://code.sololearn.com/c09qJ6jmqcRu/?ref=app
30th Apr 2018, 6:14 AM
Yugabdh
Yugabdh - avatar
0
Well it will not create global array I guess. you can access it with the help of pointers in other functions.
30th Apr 2018, 6:19 AM
Yugabdh
Yugabdh - avatar
0
YUGABDH PASHTE I was talking about new and delete, and new is some what like array
30th Apr 2018, 1:21 PM
‎ ‏‏‎Anonymous Guy
0
Okay I will create example for it in short time but malloc is also function with which you can allocate bynamic memory
30th Apr 2018, 1:23 PM
Yugabdh
Yugabdh - avatar
0
malloc was for c and new is for c++, its the same thing but better
30th Apr 2018, 1:27 PM
‎ ‏‏‎Anonymous Guy