+ 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!
7 ответов
+ 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
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
0
I modified code to run it on c++ now, hope it will help
https://code.sololearn.com/c09qJ6jmqcRu/?ref=app
0
Well it will not create global array I guess. you can access it with the help of pointers in other functions.
0
YUGABDH PASHTE I was talking about new and delete, and new is some what like array
0
Okay I will create example for it in short time but malloc is also function with which you can allocate bynamic memory
0
malloc was for c
and new is for c++, its the same thing but better