C + + dynamic allocation and revocation of memory and struct type as function parameters _c language

Source: Internet
Author: User

C + + dynamic allocation of memory (new) and undo memory (Delete)
In the process of software development, it is often necessary to dynamically allocate and undo memory space, such as inserting and deleting nodes in dynamic lists. The C language uses library functions malloc and free to allocate and revoke memory space. C + + provides a simpler and more powerful operator, new, and delete to replace the malloc and free functions.

Note: New and delete are operators, not functions, and therefore perform efficiently.

Although C + + retains the malloc and free functions in order to be compatible with C, it is recommended that users use the new and delete operators instead of the malloc and free functions. Example of the new operator:

new int; Opens a storage space that holds an integer, returns a new int (100) that points to the storage space,
and//opens a space for an integer and specifies that the integer's initial value is 100, and returns an address pointing to the storage space,
new CHAR[10] ; Open up a space for a character array (including 10 elements), return the address of the first element
new int[5][4];//Open a space that holds a two-dimensional integer array (size 5*4), returns the address of the first element
float *p=new float ( 3.14159); Create a space to hold a single precision number and specify that the initial value of the real numbers is//3.14159 and assign the address of the returned 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 an array space with new. If space is not allocated properly due to insufficient memory, new returns a null pointer, which allows the user to determine whether the allocated 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 undo the space for a single precision number that was opened with new (above), you should use

  Delete p;


Front with "new char[10];" The space of the character array that is developed, if you assign the pointer to the pointer variable PT, you should undo the space using the following form of the delete operator:

  Delete [] pt; Precede the pointer variable with a bracket that represents the operation of the array space

"Example" opens up space for storing a structural variable.

#include <iostream>
#include <string>   
using namespace std;
struct Student//Declaration struct type Student
{
  string name;
  int num;
  char sex;
};
int main ()
{
  Student *p;//defines pointer variable p=new Student to data of struct type Student
  ;//Create a space for Student-type data with the new operator
  p->name= "Wang Fun";//Assign value to member of struct variable
  p->num=10123;
  p->sex= ' m ';
  Cout<<p->name<<endl<<p->num
  <<endl<<p->sex<<endl;//Output values for each member
  delete p;//Undo the space return
  0;
}

The results of the operation are:

Wang Fun 10123 m

The figure opens up the space for new student.

In the dynamic allocation/cancellation of space, these two operators are often used in conjunction with the structure, is very effective. You can see:
To access the structure space opened with new, it cannot be done directly through the variable name, only through the pointer p. If you want to establish a dynamic linked list, you must start with the first node, each one to open the node and input the data of each node, through the pointer to establish the relationship between the front and back phase chain.

C + + structural body type as function parameter
There are 3 ways to pass data from a struct variable to another function:
Structural variables are used as parameters of the masterpiece. This method is less commonly used.
The address of a struct variable is passed to the formal parameter by using a pointer to a struct variable as an argument.
function parameters are used as reference variables of structural variables.

The following is a simple example to illustrate and compare them.

The "example" has a structural variable Stu, which contains the student number, name and 3 course results. Requires that the members are assigned values in the main function, and their values are output in another function print.

1) Using structural variables as function parameters.

#include <iostream>
#include <string>
using namespace std;
struct student//declares the struct body type Student
{
  int num;
  Char name[20];
  float score[3];
int main ()
{
  void print (Student);//function declaration, parameter type is struct Student
  Student stu;//define struct variable
  stu.num=12345;/ /The following 5 lines are assigned to the members of the structural variables
  stu.name= "Li Fung";
  stu.score[0]=67.5;
  stu.score[1]=89;
  stu.score[2]=78.5;
  Print (STU); Call the print function, output stu the values of each member return
  0;
}
void print (Student st)
{
  cout<<st.num<< "" <<st.name<< "" <<st.score[0]
  << "" <<st.score[1]<< "" <<st.score[2]<<endl;
}

The results of the operation are:

12345 Li Fung 67.5 89 78.5 (2)

2) with the reference to the structure of the variable pointer to the above program based on a slightly modified.

#include <iostream>
#include <string>
using namespace std;
struct Student
{
  int num; string name;/////string variable defined with type
  float score[3];
stu={12345, "Li Fung", 67.5,89,78.5}; Defines the structure body Student variable stu and assigns
an initial value int main ()
{
  void print (Student *);//function declaration, the parameter is a pointer variable that points to the Student type data
  Student *pt=&stu; Defines a pointer variable pt with a base type of student and points
  to Stu print (PT); The argument is a pointer variable that points to the student class data return
  0;
}
Defines a function in which the formal parameter p is a pointer variable
void print (Student *p)
{
  cout<<p->num<< "" <<p-the base type Student >name<< "" <<p->score[0]<< "" <<
  p->score[1]<< "" <<p->score[2] <<endl;
}

When the print function is invoked, the argument pointer variable PT transmits the starting address of the Stu to the formal parameter P (p is also a pointer variable of the base type student). So the formal parameter p also points to Stu, see figure.

Output the member values of the struct variables that p points to in the print function, which is the member value of the Stu. The pointer variable pt can also not be defined in the main function, and the start address of the Stu is passed to the argument p when the print function is invoked with &stu as the argument.

3) using reference of structural variables as function parameters

#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
  print (STU) of the student type variable;
  The argument is a struct student variable return
  0;
}
function definition, parameter is struct Student variable reference
void print (Student &stud)
{
  cout<<stud.num<< "" << stud.name<< "" <<stud.score[0]
  << "" <<stud.score[1]<< "" <<stud.score[2] <<endl;
}

The program (1) uses the structure variable as the actual parameter and the formal parameter, the procedure is intuitive and understandable, and the efficiency is not high.
The program (2) uses the pointer variable as the actual parameter and the formal parameter, the space and the time cost are very small, the efficiency is high. But the procedure (2) is not as direct as the program (1).
The argument of the program (3) is the student type variable of the structure body, and the reference of the formal parameter is student type, and the Stu address is passed when the actual situation is combined, thus the efficiency is higher. It has the advantages of (1) and (2).

Reference variables are used primarily as function parameters, which can improve efficiency and keep the program readable. In this example, the string method is used to define the strings variable, and in some C + + systems These programs cannot be run at this time, and the reader can modify the program so that it can run on its own system.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.