Novice Guide - Reflections

xiaoxiao2021-03-06  58

Novice guide - pointer (translation)

Original: http://www.codeproject.com/cpp/pointers.asp What is a pointer?

As with other variables, the pointer is a basic variable, which is different that the pointer contains a practical data, which represents a memory address that can find the actual information. This is a very important concept. Many procedures and ideas rely on pointers as the foundation of their design.

Start

How to define a pointer? In addition to you need to add an asterisk in front of the variable, the other and other variable definitions are the same. For example, the following code defines two pointer variables, which are pointed to an integer.

Int * pnumberone;

INT * PNUMBERTWO;

Do you notice the prefix 'P' before the two variable name? This is a convention that means that this variable is a pointer.

Now let's take these pointers to some things:

PNumberone = & Some_Number;

PNUMBERTWO = & Some_other_number;

'&' Symbols should read "What is the address", which returns a variable in the memory, set to the variable on the left. Therefore, in this example, the PNUMBERONE settings and the address of the Some_Number are the same, so PNumberOne now points to Some_Number.

Now, if we want to access the address of some_number, you can use pNumberone. If we want to access the value of some_number through PNumberone, you should use * pnumberone. This asterisk means that the reference to the pointer should read "what point to the memory area".

What have we learned now? for example

Hey, there are many things that need to be understood. My suggestion is that if you have any concepts, if you don't make it clear, then, you may wish to see it again. The pointer is a complex object, which may take a while to master it.

There is an example of an example to demonstrate the concepts of the above. This is written with C, there is no C extension.

#include

void main ()

{

/ / Statement variables

Int nnumber;

INT * PPOINTER;

// assignment

nnumber = 15;

PPOINTER = & nnumber;

/ / Output NNUMBER value

Printf ("NNUMBER IS Equal TO:% D / N", NNumber);

/ / Modify the value of nNumber through PPointer

* ppoint = 25;

// Certificate NNumber has been changed

/ / Print NNUMBER again again

Printf ("NNUMBER IS Equal TO:% D / N", NNumber);

}

Read over again, and compile sample code, so that you understand why it works. If you are ready, continue.

A trap!

See if you can find the problem of the following programs:

#include

INT * PPOINTER;

Void somfunction ();

{

Int nnumber;

nnumber = 25;

// Point PPointer to nNumber

PPOINTER = & nnumber;

}

void main ()

{

SomeFunction (); // Do something with PPOINTER

/ / Why will you fail?

Printf ("Value of * Ppoint:% D / N", * PPointer;

}

This program first calls the SomeFunction function, which creates a variable called NNumber and pointing PPOInter to it. Then, the problem is that when the function exits, nNumber is deleted because it is a local variable. The local variable is always deleted when the program executes a block block defined by a local variable. This means that when the SomeFunction function returns to the main function, the local variable will be deleted, so the PPointer will point to the original NNUMBER address, but this address is no longer a program. If you don't understand these, you re-read the scope of the role of local variables and global variables is wise. This concept is also very important. So how do we solve this problem? The answer is a way to use everyone: dynamic allocation. Please understand that the dynamic allocation of C and C is different. Since most of the programmers use C , then the following code is common.

Dynamically assigned

Dynamic allocation can be said to be the key to the pointer. You don't need to define variables, you can point the pointer to allocated memory. Perhaps this concept looks more vague, but it is really simple. The following code demonstrates how to assign memory for an integer:

INT * PNUMBER;

PNUMBER = New INT;

The first line stated that a pointer PNUMBER, the second line assigned an integer memory, and points PNumber to this new memory. Here is another example, this time uses a floating point number:

Double * PDOUBLE;

PDOUBLE = New Double;

What is the difference between dynamic allocation? When the function returns or the program is running to the current block, the memory you dynamically allocate will not be deleted. Therefore, if we use dynamic allocation to rewrite the above example, you can see that it can work normally.

#include

INT * PPOINTER;

void somefunction ()

{

// make PPointer Point to a new integer

PPOINTER = New INT;

* ppoint = 25;

}

void main ()

{

SomeFunction (); // make ppointer Point to Something

Printf ("Value of * Ppoint:% D / N", * PPointer;

}

Read over, compile the above code, so that you have understood how it works. When the SomeFunction is called, some memory is assigned and point it to it with PPointer. This time, when the function returns, the new memory is complete. Therefore, PPointer still points to useful things. This is because dynamic allocation is used. Confident that you have understood it. So, continue to look down, understand why the above programs will have a series of errors.

Memory allocation and memory release

There is a problem here that it may become very serious, although it is easy to remedy. This question is, although you can easily make memory completely free, you can not automatically delete unless you tell your computer, you will no longer need this memory, otherwise memory will always be assigned. So the result is that if you don't tell your computer, you have already used this memory, then it will become a waste of space, because other programs or other parts of your application cannot use this memory. It will eventually cause the system to crash because the memory is exhausted. So this problem is quite important. It is very easy to release after memory use:

delete ppoint;

These are what you need to do. But you must be sure, you delete a pointer to the memory you actually allocate, not any other rubbish. Memory that tries to use Delete has been dangerous and may cause the program to crash. Here again, it will be placed in this time, there will be no memory.

#include

INT * PPOINTER;

void somefunction ()

{

// make PPointer Point to a new integer

PPOINTER = New INT;

* ppoint = 25;

}

void main ()

{

SomeFunction (); // make ppointer Point to Something

Printf ("Value of * Ppoint:% D / N", * PPointer;

delete ppoint;

}

Only one line is different, but this line is the point. If you don't delete memory, it will cause "memory leak", and memory will gradually decrease, unless the application restarts, otherwise it will not be regenerated.

Pass the pointer to the function

Passing the pointer is very useful to the function, but it is not easy to master. If we write a program, pass a value and give it to 5, we might write the following procedure:

#include

Void AddFive (int Number)

{

Number = Number 5;

}

void main ()

{

INT nmynumber = 18;

Printf ("My Original Number IS% D / N", NMYNUMBER);

AddFive (NMYNUMBER);

Printf ("My New Number IS% D / N", NMYNUMBER);

}

However, the function addFive's parameter Number is just a copy of the variable NMynumber, not the variable itself, and therefore, Number = Number 5 is just a copy of the variable 5, not the variable in the main () function. Of course, you can run the program to prove this.

In order to pass the value, we can pass the pointers of this variable into the function, but we need to modify the function to pass the value of the value instead of the value. Therefore, Void AddFive (int * number) is then modified to Void AddFive (INT * NUMBER) adds an asterisk. The following is a modified function, note that we must confirm that the NMYNumber is delivered, not it itself. This is done by adding & symbols, usually reading "what address".

#include

Void AddFive (INT * NUMBER)

{

* Number = * Number 5;

}

void main ()

{

INT nmynumber = 18;

Printf ("My Original Number IS% D / N", NMYNUMBER);

AddFive (& NMYNUMBER);

Printf ("My New Number IS% D / N", NMYNUMBER);

}

Everyone can try to do an example to experiment. Note that the important asterisk in front of Number variables in the AddFive function. Just must be, used to tell the compiler We want to add 5 to the value pointing to the variable Number, not the 5 plus 5 to the pointer itself.

About the function is that you need to pay attention to you can also return a pointer. such as:

INT * myfunction (); In this example, myFunction functions return a pointer to integer.

Class pointer

There are two questions that need to be paying attention to the pointers. One is the structure or class. You can define a class as follows:

Class myclass

{

PUBLIC:

INT m_Number;

Char m_character;

}

Then you can define a class variable as follows:

MYCLASS Thing;

You should already know these, if you don't know, then read the above content again. Define the pointer to myclass should write this:

Myclass * thing;

Then you need to allocate memory and point your pointer to this memory.

. = new myclass;

The problem is coming, how do you use this pointer? In general, we write Thing.m_Number, but you can't use '.' Operations, because Thing is not a MyClass object. Just point to a pointer to a MyClass object. Therefore, the pointer Thing does not contain m_number variables. It is just that the structure it points to contains this variable. Therefore, we must use a different agreement, with-> replacing '.'. The following is an example:

Class myclass

{

PUBLIC:

INT m_Number;

Char m_character;

}

void main ()

{

Myclass * ppoint;

PPOINTER = New myclass;

PPOINTER-> m_number = 10;

PPointer-> M_Character = 's';

delete ppoint;

}

Array pointer

You can also construct a pointer to the array as follows:

INT * PARRAY;

PARRAY = New Int [6];

A pointer called PARRAY will be created, pointing to an array containing 6 elements. Another method of construct is to use dynamic allocation, as follows:

INT * PARRAY;

Int MyArray [6];

PARRAY = & myarray [0];

Note that you can use & myarray [0], you can use & myArray replacement. Of course, this is only suitable for arrays.

Use pointer to array

Once you have a pointer to the array, how do you use it? Now suppose you have a pointer to an array of integers, then the pointer will point to the first integer. For example, as follows:

#include

void main ()

{

Int arch [3];

Array [0] = 10;

Array [1] = 20;

Array [2] = 30;

INT * PARRAY;

PARRAY = & array [0];

Printf ("PARRAY POINTS to the Value% D / N", * PARRY);

}

Move the needle to the next value to the array, you can use PARRAY . Maybe you can also guess, we can use PARRAY 2 to move the pointer upward positions. What should be noted is that you must know how much the upper limit of the array is (3), because the compiler can't check if you move your pointer to an array, so you can easily crash. The following is an example, showing the three values ​​we set:

#include

void main ()

{

Int arch [3];

Array [0] = 10;

Array [1] = 20;

Array [2] = 30;

INT * PARRAY;

PARRAY = & array [0];

Printf ("PARRAY POINTS to the Value% D / N", * PARRY);

PARRAY ;

Printf ("PARRAY POINTS to the Value% D / N", * PARRY);

PARRAY ;

Printf ("PARRAY POINTS to the Value% D / N", * PARRY);

}

You can also use PARRAY-2 to move 2 locations forward. Whether it is added or decrease, you must ensure that it is not the operation of the data pointed to by the pointer. This operational pointer and array is most common in the cycle. For example, for and while loops.

In addition, if you have a pointer, such as int pNumberSet, you can also treat it as an array. For example, PNumBerset [0] is equal to * pNumBerset, and PNumBerset [1] is equal to * (PNUMBerset 1).

For arrays, there is still something to pay attention to if you use new to allocate memory, such as:

INT * PARRAY;

PARRAY = New Int [6];

You must delete it in the following way:

DELETE [] PARRAY

Note that DELETE is [], it tells the compiler, which is deleted the entire array, not just the first element. For arrays you must use this method, otherwise there will be memory leaks.

to sum up

A note: You can't delete the memory that is not allocated with new. For example, the following example:

void main ()

{

Int number;

INT * pNumber = Number;

DELETE PNUMBER; // WRONG - * PNUMBER WASN'T Allocated Using New.

}

转载请注明原文地址:https://www.9cbs.com/read-83604.html

New Post(0)