函数中new的内存的释放实例

#include
using namespace std;
const int ArSize = 80;
char * left(const char* str,int n=1);
int main()
{
char sample[ArSize];
cout << "Enter a string: "<< endl;
cin.get(sample,ArSize);
char *ps =left(sample,4);
cout << ps << endl;
delete [] ps ;
return 0;


}


char * left(const char* str,int n)
{
if(n<0)
n=0;
char * p =new char[n+1];
int i=0;
for( i=0;i {
p[i]=str[i];
}
while(i p[i++]='\0';

return p;

}

程序很简单,但很好的说明了在函数中分配的内存,在什么地方释放的问题。

new 分配内存,delete 释放内存.注意,使用delete的关键在于,将它用于new
分配的内存.这并不意味着要使用用于new的指针,而是用于new的地址
int * ps =new int;
int * pq = ps;
delete pq;

你可能感兴趣的:(C++)