- New int;//opens a storage space that holds integers, returning an address (that is, a pointer) to that storage space
- new int (100);//opens a space for storing integers and specifies that the integer has an initial value of 100 and returns an address to that storage space
- New char[10];//opens a space for storing character arrays (including 10 elements), returning the address of the first element
- New int[5][4];//opens a space for storing two-dimensional integer arrays (size 5*4), returning the address of the first element
- float *p=new float (3.14159);//Open a space for storing single-precision numbers and specifying the initial value of the real number as//3.14159, assigning the address of the returned space to the pointer variable p
- The new operator uses a general format of the new type (initial value) to allocate an array space with new without specifying an initial value. If space cannot be allocated properly due to insufficient memory, then new returns a null pointer null, which allows the user to determine whether the allocated space was successful based on the value of the pointer.
- The general format used by the delete operator is the delete [] pointer variable
- For example, to undo the space (5th above), which is opened with new, to store single-precision numbers, the delete p should be used;
- "New char[10" in front; Opens the character array space, if you assign a pointer to the pointer variable pt, the space should be undone with the following form of the delete operator:
- Delete [] pt;//in front of the pointer variable with an opposite bracket, indicating that it is an operation of an array space
1 //example opens up space to hold a struct variable. 2#include <iostream>3#include <string>4 using namespacestd;5 structStudent//declaring struct-body type student6 {7 stringname; 8 intnum; 9 Charsex;Ten }; One intMain () A { -Student *p;//A pointer variable that defines the data that points to a struct type student -p=NewStudent;//using the new operator to open up a space for storing student-type data theP->name=″wang Fun″;//assigning values to members of struct variables -p->num=10123; -p->sex='m'; -cout<<p->name<<endl<<p->num<<endl<<p->sex<<endl;//output values for each member + DeleteP//Undo the Space - return 0; + } A //running results for Wang fun 10123 m
Use of New in C + +