萌新求大佬!!!
// delete.cpp -- using the delete operator#include <iostream>
#include <cstring> // or string.h
using namespace std;
char * getname(void); // function prototype
int main()
{
char * name; // create pointer but no storage
name = getname(); // assign address of string to name
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed
name = getname(); // reuse freed memory
cout << name << " at " << (int *) name << "\n";
delete [] name; // memory freed again
// cin.get();
// cin.get();
return 0;
}
char * getname() // return pointer to new string
{
char temp; // temporary storage
cout << "Enter last name: ";
cin >> temp;
char * pn = new char;
strcpy(pn, temp); // copy string into smaller space
return pn; // temp lost when function ends
}
这一段代码中getname()函数使用过后temp与pn都被释放,那为什么主函数main()中name得到指针后还可以显示pn所代表的字符串,
pn不是已经被释放了吗??
pn 是被释放了,但是 pn 指向的对象没有释放,pn 指向的对象是 new 出来的,只要没有 delete,直到程序结束,都一直存在
页:
[1]