Home>

C++ dynamically allocate memory (new) and deallocate memory (delete)

During software development,It is often necessary to dynamically allocate and deallocate memory space,For example, the insertion and deletion of nodes in a dynamic linked list.In C language, the library functions malloc and free are used to allocate and deallocate memory space.C++ provides simpler and more powerful operators new and delete to replace malloc and free functions.

Note:new and delete are operators,Is not a function,Therefore, the execution efficiency is high.

Although for compatibility with the C language,C++ still retains malloc and free functions, but users are advised not to use malloc and free functions, but to use new and delete operators. Example of the new operator:

new int;//Open up a storage space for integers,Returns an address (that is, a pointer) to the storage space
new int (100);//Open up a space for integers,And specify the initial value of the integer as 100, and return an address pointing to the storage space
new char [10];//Open up a space for the character array (including 10 elements), and return the address of the first element
new int [5] [4];//Open up a space for a two-dimensional integer array (size 5 * 4) and return the address of the first element
float * p=new float (3.14159);//Open up a space for single-precision numbers,And specify that the initial value of the real number is //3.14159, and assign the returned address of the space to the pointer variable p

The general format used by the new operator is:

 new type [initial value];

You cannot specify an initial value when allocating array space with new.If space cannot be allocated normally due to insufficient memory, etc.,Then new will return a null pointer null, and the user can judge whether the allocation of space is successful based on the value of the pointer.

The general format used by the delete operator is:

 delete [] pointer variable

For example, to revoke the space for single precision numbers opened above with new (the first example above,Should use

 delete p;

The character array space opened with "new char [10];"If the pointer returned by new is assigned to the pointer variable pt, the space should be undone with the delete operator of the following form:

 delete [] pt;//Put a pair of parentheses in front of the pointer variable,Representation is an operation on array space

[Example] Create space to store a structure variable.

#include<iostream>
#include<string>
using namespace std;
struct student //declares the structure type student
{
  string name;
  int num;
  char sex;
};
int main ()
{
  student * p;//Define a pointer variable to the data of the structure type student
  p=new student;//Use the new operator to open a space for student data
  p->name="wang fun";//Assign a value to a member of a structure variable
  p->num=10123;
  p->sex="m";
  cout<p->name<endl<p-&num
  <endl<<p->sex<endl;//Output the value of each member
  delete p;//Cancel the space
  return 0;
}

The result is:

wang fun 10123 m

The picture shows the space opened by new student.

When space is dynamically allocated/deallocated,These two operators are often combined with structs,Is very effective.can be seen:

To access the structure space opened with new,It cannot be done directly by the variable name,Only accessible via pointer p.If i want to build a dynamic linked list,Must start at the first node,Open the nodes one by one and enter the data of each node.The relationship between the front and back phase chains is established through the pointer.

C++ structure type as function parameter

Pass data from a structure variable to another function,There are three methods:

Use structure variable names as parameters.This method is rarely used.

Take a pointer to a structure variable as an argument,Pass the address of the structure variable to the formal parameter.

Use the reference variable of the structure variable as the function parameter.

Here is a simple example to illustrate,And compare them.

[Example] There is a structure variable stu, which contains the student's student number, name and grades of 3 courses.It is required to assign values ​​to members in the main function,Print their values ​​in another function print.

1) Use structure variables as function parameters.

#include<iostream>
#include<string>
using namespace std;
struct student //declaration structure type student
{
  int num;
  char name [20];
  float score [3];
};
int main ()
{
  void print (student);//Function declaration,Parameter type is structure student
  student stu;//Define structure variables
  stu.num=12345;//The following 5 lines assign values ​​to members of the structure variable
  stu.name="li fung";
  stu.score [0]=67.5;
  stu.score [1]=89;
  stu.score [2]=78.5;
  print (stu);//Call the print function and output the value of each member of the stu
  return 0;
}
void print (student st)
{
  cout<st.num<<<<st.name<<<<st.score [0]
  <""<st.score [1]<"<<st.score [2]<endl;
}

The result is:

12345 li fung 67.5 89 78.5 (2)

2) Use the pointer to the structure variable as the actual parameter and modify it slightly based on the above program.

#include<iostream>
#include<string>
using namespace std;
struct student
{
  int num;string name;//Define string variable with string type
  float score [3];
} stu={12345, "li fung", 67.5,89,78.5};//Define the structure student variable stu and assign an initial value
int main ()
{
  void print (student *);//function declaration,The parameter is a pointer variable to student data
  student * pt =&stu;//Define a pointer variable pt whose base type is student and point to stu
  print (pt);//The argument is a pointer variable to the data of the student class
  return 0;
}
//define the function,The parameter p is a pointer variable whose base type is student
void print (student * p)
{
  cout<p-#<"<<p->name<<"
  p->score [1]<"<<p->score [2]<endl;
}

When the print function is called, the argument pointer variable pt passes the starting address of stu to the formal parameter p (p is also a pointer variable with base type student). In this way, the parameter p also points to stu, as shown in the figure.

Print the member values ​​of the structure variables pointed to by p in the print function.They are also members of stu.It is also possible to not define a pointer variable pt in the main function, and use&stu as an argument when calling the print function.Pass the starting address of stu to the argument p.

3) Use a reference to a structure variable as a function parameter

#include<iostream>
#include<string>
using namespace std;
struct student
{
  int num;
  string name;
  float score [3];
} stu={12345, "li li", 67.5,89,78.5};
int main ()
{
  void print (student);
  //function declaration,The parameter is a reference to a student variable
  print (stu);
  //The actual parameter is a structure student variable
  return 0;
}
//function definition,The parameter is a reference to the structure student variable
void print (student&stud)
{
  cout<stud.num<<<<stud.name<<<<stud.score [0]
  <""<stud.score [1]<""<stud.score [2]<endl;
}

Program (1) uses structure variables as actual and formal parameters.The program is intuitive and easy to understand.Efficiency is not high.

Program (2) uses pointer variables as actual and formal parameters.Space and time overhead are small,Higher efficiency.But program (2) is not as straightforward as program (1).

The argument of program (3) is a structure student type variable,The formal parameter uses the student type reference,The address of stu is passed during the combination of virtual and real, so it is more efficient.It has the advantages of (1) and (2).

Reference variables are mainly used as function parameters,It can increase efficiency,And keep the program readable.In this example, the string method is used to define a string variable.These programs cannot currently be run on some c++ systems,The reader can modify the program,Make it work on the system you use.

c
  • Previous Win Server 2008 R2 with PowerShell
  • Next C ++ structure definition and initialization and variable reference