❶基本格式:
int * pn = new int;
delete pn; //释放pn指向的内存,但是不会删除指针pn本身,可以讲pn重新指向一块新的内存块
❷new的基本使用实例:
#include <iostream>
using namespace std;
int main()
{
int *pn = new int;
*pn = 1001;
cout << "the value of *pn is " << *pn << endl;
cout << "the address of pn is " << pn << endl;
delete pn;
}
❸使用new创建动态数组:
基本格式:
int *psome = new int [10];
delete [] psome;
❹new创建动态数组的实例:
#include <iostream>
using namespace std;
int main()
{
int *p_int = new int [3];
p_int[0] = 0;
p_int[1] = 1;
p_int[2] = 2;
cout << "p_int[1] = " << p_int[1] << endl;
p_int++;
cout << "now p_int[1] is " << p_int[1] << endl;
p_int--; //指针回到开始的地方
delete [] p_int; //释放数组所占的内存
return 0;
}
❺new创建动态结构体:
a.用new创建动态结构体时,访问结构体成员的方法有两种:
struct student
{
char name[20];
float Math;
float Chiese;
};
student *liu = new student;
cout << "Enter the name: ";
cin >> liu->name; //或者 cin >> (*liu).name;
b.使用new创建动态结构体实例:
#include <iostream>
using namespace std;
struct student
{
char name[20];
float Math;
float Chinese;
};
int main()
{
student *zhang = new student;
cout << "Enter name of the student: ";
cin.get(zhang->name,20);
cout << "Enter the math score of the student: ";
cin >> (*zhang).Math;
cout << "Enter the Chiness score of the student: ";
cin >> zhang->Chinese;
cout << "Name: " << zhang->name << endl;
cout << "Math score: " << (*zhang).Math << endl;
cout << "Chinese score: " << zhang->Chinese << endl;
return 0;
}
c.区别什么时候用点(.)什么时候用箭头成员运算符(->):如果结构标识符是结构名,则使用点运算法;如果标识符是指向结构的指针,则用->
struct student
{
float Math;
float Chinese;
};
student zhang =
{
100.0,
99.5
};
student *new_zhang = &zhang;
cout << zhang.Math;//用点运算符
cout << new_zhang->Math;//用->
❻new创建动态结构体数组:
实例:
#include <iostream>
using namespace std;
struct CandyBar
{
char name[20];
float weight;
int calory;
};
int main()
{
CandyBar *p_candy = new CandyBar[3]
{
{
"snack1",
11.11,
12
},
{
"snack2",
12.22,
13
},
{
"snack3",
13.33,
15
}
};
cout << "The name of the first candy is " << p_candy[0].name << endl;
cout << "The calory of the second candy is " << p_candy[1].calory << endl;
cout << "The weight of the third candy is " << p_candy[2].weight << endl;
delete [] p_candy;
return 0;
}
❼new和delete使用时应遵守的原则:
a.不能使用delete释放不是由new分配的内存
b.不能使用delete释放同一个内存块两次
c.如果使用new []为数组分配内存,则应使用delete []来释放内存
d.如果使用new为一个实体分配内存,则应使用没有[]的delete来释放内存
e.对空指针使用delete是安全的