The usage of new and delete in C++

  • 2020-05-30 20:55:24
  • OfStack

The usage of new and delete in C++

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

new usage:

1. Create a single variable address space

1) new int; int *a = new int assigns an address of type int to the integer pointer a.

2)int *a = new int(5) ACTS the same as above, but assigns the integer to 5

2. Open up array space

Dimension 1: int *a = new int[100]; Open up an integer array of size 100

2 d: int **a = new int[5][6]

3 dimensions and above: and so on.

1 general usage: new type [initial value]

delete usage:

1. int *a = new int;

delete a; // free the space of a single int *a = new int[5];

delete [] a; // free the int array space

Access to the structure space created by new cannot be done directly by variable names, but only by assigned Pointers.

You can use new and delete to dynamically open up and undo the address space. If you run out of a variable (1 is usually an array that is temporarily stored) and need to use it again the next time you're programming, but you want to save the reinitialization effort, you can open up a space each time you start using it, and then undo it when you're done using it.

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!

Related articles: