Question:
Pointers doubt ... why use new and delete?
anonymous
2014-02-16 05:14:07 UTC
int*ptr[80];
int*ptr=new int[80];
......
What is the difference...
Basically where do we use new and and where simply static initialization.....
What does delete do.....
Why not simple static variables like int , char have an delete option....
If i do static initialization of an pointer ... do i need to use delete...
Three answers:
justme
2014-02-16 06:22:51 UTC
I think what you mean is:

int ptr[80]; this allocates 80 ints

instead of:

int *ptr[80]; which allocates 80 pointers to ints



int *ptr = new int[80]; allocates a pointer to 80 ints



But anyway, using new and delete you can dynamically allocate memory which HAS to be freed with delete. You cant do that with int ptr[80].



Why would you do one over the other?



if the length of the array is fixed and known at compile time then:



int ptr[80];





If it is not known then use new and delete:



int a;

cout<<"enter length";

cin>>a;

int *ptr = new int[a]; <------------ a could be any number





Another advantage is where the variable is stored.



int ptr[80]; is on the stack which is somewhat limited. When the stack is no longer needed the whole stack is freed automatically.



int *ptr = new int[80]; is stored in RAM which is allocated from the free memory pool, which is why you must delete when you are done with it. Using delete frees the memory and returns it back to the memory pool.



Basically using new is the same as using malloc, and delete is the same as using free.
?
2014-02-17 09:49:55 UTC
int *ptr[80]; make 80 int type pointer

int *ptr=new int[80]; gives a address of 80 array in ptr pointer

pointer is like dynamic allocation so it can be deleted.

if make static pointer you can delete if want
?
2014-02-16 13:24:33 UTC
you can ask the difference in stackoverflow



i think you may know it(stack overflow),



if you dont no about it ask there and while asking u should follow some proper things like font,

details ,



i cant answer your question because i dont no ,



i asked one question which is below , please suggest me one answer :)



https://answersrip.com/question/index?qid=20140216051127AAjOR9b


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...