目录
new delete
不能继续使用malloc free,等到类的时候free不可以完成工作,这个之后再说
变量
#include <iostream>
using namespace std;
struct A
{
int num;
int num2;
};
int main()
{
//为num在堆上开辟空间
int* num = new int;
*num = 10;
cout << num << endl; //10
//开辟空间时初始化
int* num2 = new int(10);
cout << num2 << endl; //10
//结构体开辟空间初始化
A* a = new A{10,20};
cout << a->num << " " << a->num2 << endl; //10 20
delete num;
delete num2;
delete a;
return 0;
}
数组
#include <iostream>
using namespace std;
struct A
{
int num;
int num2;
};
int main()
{
//动态开辟数组
int* arr = new int[3]{1,2,3};
for(int i = 0;i < 3;++i)
{
cout << arr[i] << " ";
}
cout << endl;
//自定义类型
A* a = new A[3]{{1,2},{3,4},{5,6}};
for(int i = 0;i < 3;++i)
{
cout << a[i].num << " " << a[i].num2 << endl;
}
//二维数组
int(*arr2)[4] = new int[3][4]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
for(int i = 0;i < 3;++i)
{
for(int j = 0;j < 4;++j)
{
cout << arr2[i][j] << " ";
}
cout << endl;
}
cout << endl;
delete[]arr;
delete[]a;
delete[]arr2;
return 0;
}
指针数组
#include <iostream>
#include <string.h>
using namespace std;
struct A
{
int num;
int num2;
};
int main()
{
char** str = new char*[3]{"hello","world","china"};
for(int i = 0;i < 3;++i)
{
cout << str[i] << endl;
}
char** str2 = new char*[3];
for(int i = 0;i < 3;++i)
{
str2[i] = new char[64];
}
strcpy(str2[0],"hello");
strcpy(str2[1],"world");
strcpy(str2[2],"china");
for(int i = 0;i < 3;++i)
{
cout << str2[i] << endl;
}
for(int i = 0;i < 3;++i)
{
delete[]str2[i];
}
delete[]str2;
return 0;
}
这只是简单介绍,delete的时候需要注意防止的事情C中说过,等遇到具体问题的时候我会在细说,主要是今天好困,懒了哈哈!