64,282
社区成员
发帖
与我相关
我的任务
分享
// Code::Blocks 8.02 + mingw32-g++.exe
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 初始化变量
const char text[] = "const char"; // 长度为10+1
char p1 [] = "I'm p1"; // 长度为6+1
char * p2 = new char[100]; p2 = "I'm P2"; // 长度为5或100
char * p3 = (char*)malloc(100); p3 = "I'm P3";// 长度为5或100
// 显示参数
cout << "After Construct && Before Delete\n";
cout << "name" << "\t" << "Address" << "\t\t" << "Length" << "\t" << "Details" << endl
<< "text[]" << "\t" << &text << "\t" << sizeof(text) << "\t" << text << endl
<< "p1" << "\t" << &p1 << "\t" << strlen(p1) << "\t" << p1 << endl
<< "p2" << "\t" << &p2 << "\t" << strlen(p2) << "\t" << p2 << endl
<< "p3" << "\t" << &p3 << "\t" << strlen(p3) << "\t" << p3 << endl
<< endl;
// 使用delete或者free删除
delete [] text; delete text; // 纠结,为什么delete个const也不提示错啊
delete [] p1; delete p1; // 重复delete这么多次也不报错?
delete [] p2; delete p2;
delete [] p3; free(p3); delete p3;
// 显示参数 昨delete过后也还能继续运行啊?不报错也能正常显示数据?
cout << "After Construct && Before Delete\n";
cout << "name" << "\t" << "Address" << "\t\t" << "Length" << "\t" << "Details" << endl
<< "text[]" << "\t" << &text << "\t" << sizeof(text) << "\t" << text << endl
<< "p1" << "\t" << &p1 << "\t" << strlen(p1) << "\t" << p1 << endl
<< "p2" << "\t" << &p2 << "\t" << strlen(p2) << "\t" << p2 << endl
<< "p3" << "\t" << &p3 << "\t" << strlen(p3) << "\t" << p3 << endl
<< endl;
return 0;
}
/********** 结果 ****************
****************
After Construct && Before Delete
name Address Length Details
text[] 0x28ff20 11 const char
p1 0x28ff10 6 I'm p1
p2 0x28ff0c 6 I'm P2
p3 0x28ff08 6 I'm P3
After Construct && Before Delete
name Address Length Details
text[] 0x28ff20 11 const char
p1 0x28ff10 6 I'm p1
p2 0x28ff0c 6 I'm P2
p3 0x28ff08 6 I'm P3
Process returned 0 (0x0) execution time : 0.140 s
Press any key to continue.
*****************************************************/