Thorough understanding of pointer arrays, array pointers, and function pointers, as well as allocation rules in the heap

Source: Internet
Author: User
Tags arrays constructor
One: Memory allocations for pointers and heaps
Let's start with the pointer: A pointer type, which in theory contains the address of other variables, so some books also call it: Address variable. Since the pointer is a type, it is the size of the type, on the Dahne server or on a normal PC, is 4 bytes in size, inside just stored a variable address. Regardless of the type of pointer, char *, int *, int (*), String *, float *, all of which indicate what type of address space this pointer is pointing to, and understand that all of this basic problem seems to be reasonable.

In C + +, the application and release of the allocated storage space in the heap is done using the two operators of new and delete, respectively:
Pointer type pointer variable name =new pointer type (initialize);
Delete pointer name;
For example:

1, int *p=new int (0);
It is roughly equivalent to the following code sequence:

2, int tmp=0, *p=&tmp;
Difference: P points to a variable that is allocated by the library operator new () in the heap area of memory, and that object is not named.

Here is a description of the new operation: part of the <<c++ object-oriented development >>

1. The new operator returns a pointer to the assigned type variable (object). The variable or object that you create is indirectly manipulated by that pointer, and the dynamically created object itself has no name.

2, the general definition of variables and objects to be named after the name of the object, called named objects, and dynamically called nameless objects (note the difference between the temporary objects in the stack, the two are completely different: different lifetimes, different methods of operation, temporary variables are transparent to the programmer).

3, the heap area is not automatically initialized at the time of allocation (including clear 0), so it must be initialized (initializer) to explicitly initialize. The action sequence of the new expression is as follows: The object is allocated from the heap, and the object is initialized with the value in parentheses.

Here is the request array from the heap

1. Apply for array space:
Pointer variable name =new type name [subscript expression];
Note: "Subscript expression" is not a constant expression, that is, its value does not have to be determined at compile time and can be determined at run time. This is a very significant feature of the heap, sometimes the programmer itself does not know how much memory to apply, the heap becomes particularly useful.

2. Free up array space:
Delete [] pointer variable name to the array;
Note: The square brackets are very important, if the DELETE statement is less square brackets, because the compiler thinks that the pointer is to the first element of the array, it will produce the problem of recycling (only the space occupied by the first element is recycled), we usually call it "memory leak", add square brackets to the pointer to the array, Reclaims the entire array. Delete [] square brackets do not need to fill in the number of array elements, the system knows. Even if it is written, the compiler ignores it. <<think in C++>> said that the previous delete [] in the square brackets is the number must be added, and later because it is easy to make mistakes, so the later version improved the flaw.

Here is an example of a VC on the compile through

#include <iostream>
using namespace Std;
#include <iostream.h>//for VC
#include <string.h>
void Main () {
int n;
Char *p;
cout<< "Please enter the number of elements in the dynamic array" <<endl;
cin>>n; N is determined at run time, you can enter 17
P=new Char[n]; Request a memory space of 17 characters (8 characters and one terminator) strcpy (PC, "Dynamic allocation of heap memory");//
cout<<p<<endl;
Delete []p;//frees the memory space of the N characters pointed to by the PC return; }

Make heap space through pointers, several possible problems in programming

1. Dynamic allocation failed. Returns a null pointer (NULL) indicating that an exception occurred, insufficient heap resources, and allocation failure.
data = new double [m]; Application space
if (data) = = 0) ...//or ==null

2. Pointer deletion is freed from heap space. Deleting a pointer p (delete p;) actually means deleting the target referred to by P (variable or object, etc.), freeing up the heap space it occupies, rather than deleting p itself, releasing the heap space, p becomes a null-dangling pointer, no longer uses the space through P, and can no longer use p directly before re-assigning p.

3. Memory leak and re-release. New is paired with delete, and delete only frees heap space. If the value of the pointer returned by new is lost, the allocated heap space cannot be reclaimed, which is called a memory leak, and a duplicate release of the same space is also dangerous because the space may have been allocated separately, and the time to release it will result in a hard-to-find run-time error. Therefore, the new returned pointer must be kept properly to ensure that no memory leaks occur and that heap memory space is not repeatedly freed.

4. The lifetime of a dynamically allocated variable or object. The life of a nameless variable does not depend on its scope, such as a dynamic object created in a function that is still available after the function returns. This is why we also call the free space for the heap space. However, you must remember to release the heap space of the object, and can only be freed once, built within the function, and release outside the function is a very easy to get out of control, often error, so never in the function body to request space, let the caller release, this is a bad practice. How careful you are, you may bring mistakes.
class to request memory in the heap:
Objects created through new to invoke the constructor, delete the object by Deletee to invoke the destructor.
Cgoods *pc;
Pc=new Cgoods; Allocate heap space and construct a nameless object
The Cgoods object;
.......
Delete pc; First, the memory space is then returned to the heap, and the lifetime of the heap object does not depend on its scope, so unless the program ends, the lifetime of the heap object (The Nameless object) does not expire, and the heap object needs to be explicitly refactored with the DELETE statement, when the heap object above executes the DELETE statement, C + + Its destructor is automatically called.
Because constructors can have parameters, the class type after new can also have parameters. These parameters are the parameters of the constructor.
But for an array to be created, there are no parameters and only the default constructor is called. See the following example class description:

Class cgoods{
Char name[21];
int Amount;
float price;
float Total_value;
Public
Cgoods () {}; The default constructor. Because there are already other constructors, the system no longer automatically generates a default construct, which must be explicitly declared. Cgoods (char* name,int amount, float price) {
strcpy (Name,name);
Amount=amount;
Price=price;
Total_value=price*amount; }
......} ;//End of class declaration
Here is the invocation mechanism:

void Main () {
int n;
Cgoods *PC,*PC1,*PC2;
Pc=new cgoods ("Hello", 10,118000);
Call the three-parameter constructor pc1=new cgoods (); Call the default constructor cout<< "Enter the number of elements in an array of commodity classes" <<endl;
cin>>n;
Pc2=new Cgoods[n];
Dynamically set up arrays, cannot initialize, call N-Times default constructors
......
Delete pc;
Delete PC1;
delete []PC2; }

The constructor function is run after the application of the heap space;
The destructor runs before releasing the heap space;
Again: Creating an array of objects from the heap, you can call only the default constructor, and you cannot call any other constructors. If you do not have a default constructor, you cannot create an array of objects.

---------------------Let's take a look at the pointer array and the SET pointer ―――――――――――――
If you want to understand pointers it is best to understand the following formula:
(1) The type that the int*ptr;//pointer points to is int

(2) The type that the char*ptr;//pointer points to is Char

(3) The type that the int**ptr;//pointer points to is int* (i.e. an int * type pointer)

(4) int (*ptr) [the type that the 3];//pointer points to is an int () [3]//Two-D pointer declaration

(1) Array of pointers: An array holds the same type of pointer, which we usually call an array of pointers.
such as int * a[10]; it put 10 int * Type variable, because it is an array, already in the stack area allocated 10 (int *) space, that is, 32-bit machine is 40 byte, each space can hold an int variable address, At this point you can initialize each element of the array, either in, or in a separate loop, to initialize it.
Example:
int * a[2]={new int (3), new Int (4)}; Declare an int * array in the stack, and each of its elements applies a nameless variable in the heap, and initializes them to 3 and 4, noting that such a declaration is defective, and the VC will error
For example:
int * a[2]={new int[3],new int[3]};
Delete A[0];
Delet a[10];
However, I do not recommend that the students in this writing, may cause ambiguity, not a good style, and in the VC will error, should be written as follows:
int * A[2];
a[0]= New Int[3];
A[1]=new Int[3];
Delete A[0];
Delet a[10];
This kind of application memory style feel more in line with everyone's habit; because it is an array, you cannot delete A; compilation warns you. Delete A[1];
Note that this is an array and cannot be delete [];

(2) Array pointer: A pointer to a one-dimensional or multidimensional array;
int * B=new INT[10]; Pointer to a one-dimensional array B;
Note that this time to release the space must be delete [], otherwise it will cause memory leaks, B becomes an empty cantilever pointer.

int (*B2) [10]=new int[10][10]; Note that the B2 here points to the first address of a two-dimensional array of int.
Note: Here, B2 is equivalent to a two-dimensional array name, but does not indicate its bounds, that is, the number of elements of the highest dimension, but its minimum number of dimensions must be specified. Just like a pointer to a character, which is equivalent to a string, do not refer to a pointer to a character as a pointer to a string. This is consistent with the nesting definition of the array.
int (*B3) [30] [20]; A three-level pointer ――> A pointer to a three-dimensional array;
int (*B2) [20]; second-level pointers;
b3=new int [1] [20] [30];
b2=new int [30] [20];
Two arrays are made up of 600 integers, which are three-dimensional arrays with only one element, each with a two-dimensional array of 30 rows and 20 columns, and the other a two-dimensional array with 30 elements, one-dimensional array of 20 elements for each element.
Delete these two dynamic arrays using the following formula:
delete [] B3; Delete (release) a three-dimensional array;
delete [] B2; Delete (release) a two-dimensional array;
Again: The type of b2 here is int (*), which represents a pointer to a two-dimensional array.
B3 represents a pointer to (a pointer to a two-dimensional array), which is a level three pointer.

(3) Pointer to level two pointer
Look at the following example:
int (**p) [2]=new (Int (*) [3]) [2];
P[0]=new int[2][2];
P[1]=new int[2][2];
P[2]=new int[2][2];
Delete [] p[0];
Delete [] p[1];
Delete [] p[2];
delete [] p;
Note that the pointer type in this place is int (*), and when this problem is taken, the outer [2] is removed first, then the int * * P=new int (*) [n] is applied, and then the outer [2] is appended;
P represents a pointer to a level two pointer, and when it applies for space, pay attention to the type of pointer, that is, Int (*) represents a level two pointer, and INT (* *) is the name of a pointer to a two-level pointer. Since it is the pointer to apply space in the heap, the first thing to define is its scope: (int (*) [n]) [2],n a two-level pointer, where the lowest dimension of each two-level pointer is 2 elements. (because the minimum dimension of a two-level pointer must be specified, as mentioned above). Then we were p[0],p[1],p[2] ... In the heap allocated space, especially to note is: In the release of memory must be p[0],p[1],p[2], alone delete[], or will cause memory leaks, in delete[]p must first delete p[0]; Delete P[1], and then release the space for p application to delete [] p ... This will prevent memory leaks.

(3) The pointer of the pointer;
int * * CC=NEW (int*) [10]; Declare an array of 10 elements, each element of which is an int * pointer, and each element can also request space separately, because the CC type is a int* type pointer, so you need to apply in the heap with an int * to apply;
See below for examples (VC & GNU compilers have all passed);
int * * a= new int * [2]; Apply for space of two int * type
A[1]=new Int[3]; The second element of a applies for 3 int space, a[1] points to this space at the first address
A[0]=new Int[4]; For the first element of a, another 4 int space is applied, a[0] points to the first address of this space
int * b;

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.