A brief analysis of the usage of new and delete in c++

  • 2020-04-02 01:32:41
  • OfStack

The new and delete operators are used to dynamically allocate and undo memory

The new usage:

1. Create a single variable address space
1) new int.   Int *a = new int means that an address of type int is assigned to an integer pointer a.  

2)int *a = new int(5)

2. Open up array space
One dimension: int *a = new int[100]; Creates an integer array of size 100
Int **a = new int[5][6]
Three dimensions and above: and so on.

General usage: new type [initial value]

The delete usage:

1. Int *a = new int;
Delete a;     // frees the space of a single int

2. Int *a = new int[5];
The delete [] a; // frees the int array space

To access the struct space created by new, you cannot do this directly through the variable name, but only through the assigned pointer.

If you run out of variables (typically arrays stored temporarily) and need to use them again, but you want to save reinitialization, you can create a space each time you start using it, and then undo it when you're done.


Related articles: