New and delete can dynamically create arrays and delete arrays.
Char *a = new Char;
Delete A;
Char *a = new CHAR[12]//Create a 12-byte character array
delete [] A;
int *a = new INT[12]; Create an array of 12 byte-shaped
delete [] A;
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int Main () { int *a = new INT[10]; for (int i = 0; i < ten; I + +) { A[i] = i; } for (int i = 0; i < ten; I + +) { cout << a[i] << Endl; } delete [] A; return 0;}
Creating a two-dimensional array
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int Main () { int **a = new int* [ten]; Note that the previous pointer is higher than the next pointer for (int i = 1; I <=; i + +) { //two-D pointers are created as a Villivi. a[i-1] = new int[i]; } for (int i = 1; I <=; i + +) {for (int j = 0; J < i; J + +) { A[i-1][j] = i; } } for (int i = 1; I <=; i + +) {for (int j = 0; J < i; J + +) { cout << a[i-1][j]<< ""; } cout << Endl; } for (int i = 1; I <=; i + +) {//two-D pointer deletion is to delete a one-dimensional pointer before deleting a two-dimensional pointer. Delete [] a[i-1]; } delete [] A; return 0;}
Attention:
Use new in the constructor to initialize the pointer to the object, you should use delete in the destructor.
New and delete must be compatible with each other. The new corresponds to delete,new [] corresponding to delete [].
If you have more than one constructor, you must use new in the same way, either with brackets or without. Because there is only one destructor, all constructors must be compatible with it. However, you can use new in one constructor to initialize the pointer, and the pointer is initialized to NULL in another constructor, because the delete can be used with a null pointer.
New and delete