1.new 和delete的用法与作用:
(1.1)new的用法:指针变量 = new 数据类型;
(1.2)new的作用:申请到一段指定数据类型大小的内存
#include<iostream>
using namespace std;
int main()
{
int *p = nullptr;
p = new int;
cout <<"*p = "<< *p <<endl;
return 0;
/*注意此时*p输出的数为随机数*/
}
(2.1)delete的用法:delete 指针变量;
(2.2)delete的作用:delete将释放指针指向的内存单元
#include<iostream>
using namespace std;
int main()
{
int *p = nullptr;
p = new int;
cout <<"*p = "<< *p <<endl;
delete p;
p = nullptr;/*防止成为野指针*/
return 0;
}
2.用new和delete来实现斐波那契数列的前20个数的输出:
#include <iostream>
using namespace std;
// 1 1 2 3 5 8 13 ...
void fibonacci(int num)
{
int *data = new int[num];
if(data == nullptr)
return ;
for(int i = 0; i < num; ++i)//由于++i比i++运行更快
{
if(i == 0)
{
data[i] = 1;
}
else if(i == 1)
{
data[i] = 1;
}
else
{
data[i] = data[i - 1] + data[i - 2];
}
}
for(int i = 0; i < num; ++i)
{
cout << data[i] <<" ";
}
cout << endl;
delete[] data;/*释放内存*/
data = nullptr;/*防止成为野指针*/
}
int main()
{
fibonacci(50);
return 0;
}