question on "new" and " delete" operator

hi , here i have some difficulty.. below is a code i wrote.

#include

int main()
{
cout<<"enter the no";
int n;
cin>>n;

int *p=new int[n];

for(int i=0;i>*(p+i);

delete p;
for(int i=0;i<n;i++)
cout<<*(p+i);


}
i was trying to learn "new" and "delete" .this is giving the output whatever i am inputting.but if u look i have usued "delete p" before printing.so memory is lost. then how it could give the output?

Comments

  • : hi , here i have some difficulty.. below is a code i wrote.
    :
    : #include
    :
    : int main()
    : {
    : cout<<"enter the no";
    : int n;
    : cin>>n;
    :
    : int *p=new int[n];
    :
    : for(int i=0;i>*(p+i);
    :
    : delete p; [red]// try delete [] p;[/red]
    : for(int i=0;i<n;i++)
    : cout<<*(p+i);
    :
    :
    : }
    : i was trying to learn "new" and "delete" .this is giving the output whatever i am inputting.but if u look i have usued "delete p" before printing.so memory is lost. then how it could give the output?
    :
    :



  • no, it is not working. i donot understand why it is not deleting.
  • : hi , here i have some difficulty.. below is a code i wrote.
    :
    : #include
    :
    : int main()
    : {
    : cout<<"enter the no";
    : int n;
    : cin>>n;
    :
    : int *p=new int[n];
    :
    : for(int i=0;i>*(p+i);
    :
    : delete p;
    : for(int i=0;i<n;i++)
    : cout<<*(p+i);
    :
    :
    : }
    : i was trying to learn "new" and "delete" .this is giving the output whatever i am inputting.but if u look i have usued "delete p" before printing.so memory is lost. then how it could give the output?

    As far as I know, calling delete only says to the OS "hey, i dont need this memory anymore, you can allocate it elsewhere". It doesn't change the data that was stored in that memory address, nor does it change the variable. So the variable still points to the same data in the same memory space, it just doesnt own it anymore so there is a chance some other program will end up changing it eventually.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories