Beginner pointer guide

zhaozj2021-02-16  48

Author: Andrew Peace Original link: http: //www.codeproject.com/cpp/pointers.asp Click to download the complete source code

What is a pointer?

The pointer is basically the same as other variables, the only point difference is that the pointer does not contain actual data, but includes an address pointing to the memory location, you can find some information in this address. This is a very important concept, and many programs or ideas are the design foundation for their design, such as a list.

begin

How to define a pointer? Hey, just like defining other variables, but you still need to add an asterisk before the variable name. For example, the following code creates two pointers pointing integers: int * pNumBerone; INT * PNUMBERTWO; Do not pay attention to the prefix "P" of the variable name? This is a habit of writing code to indicate that this variable is a pointer. Now let's point these pointers to some actual values: pnumberone = & some_number; pnumbertwo = & some_other_number; "&" flag should read "The address of (...", its role is to return a variable memory Address, not this variable itself. So in this example, PNumberone is the address of Some_Number, also known as PNumberone points to Some_Number. Now, if we want to use some_number's address, then we can use PNumberone. If we want to use the value of Some_Number via PNumberone, we can use * pNumberone. "*" You should read "The Memory Location Pointed to by" "pointing to the memory location)", it is used to obtain the value points to the pointer. However, the exception of the pointer declaration, such as "int * pnumber".

What I learned now (an example):

call out! I have to understand what I have, so I suggest that if you still don't understand the above concept, then it is best to read again; the pointer is a complex topic, to master it is going to spend some time. Here is an example that explains the concepts discussed above. It is written by C and does not extension of C . #include void main () {// declared variable: int nNumber; int * ppoint; // present, give them: nnumber = 15; ppointer = & nnumber; // Print NNumber: Printf (" NNumber is equal to:% d / n ", nnumber); // Now, the nNumber: * ppoint = 25; // demonstrates that the value of nNumber has changed after passing the above code: Printf (" NNumber IS Equal to:% d / n ", nnumber);} Please read and compile the above code, and be confident that you have already understood how it works. Then, when you are ready, let's read it!

trap!

See if you can point out the shortcomings of the following procedures: #include int * ppoint int * ppoint; void somefunction () {int nNumber; nnumber = 25; // Remove PPointer to nNumber: ppoint = & nnumber;} void main () {SomeFunction (); // Let PPointer point to some things // why will this fail? Printf ("Value of * PPointer:% D / N", * ppoint);} This program first calls the SomeFunction function, created a variable named nNumber, and points PPointer to this variable. So, this is the problem. When the function ends, because nNumber is a local variable, it will be destroyed. This is because the local variables defined in the block are destroyed when the language block is completed. This means that when SomeFunction returns to main (), that variable has been destroyed, so PPointer will point to a memory location that is no longer a program. If you don't understand this, then you should read something about local variables, global variables, and scope, which is very important. So how do I solve this problem? The answer is to use a technique called dynamic allocation. Please note: At this point, C and C are different. Since most developers are using C , then the following code uses C to write. Dynamically assigned

Dynamic allocation may be a key technique for pointers. It is used to allocate memory without defining a variable, then pointing by a pointer to this memory. Although this concept seems to be confused, it is very simple. The following code explained how to allocate memory space for an integer: int * pNumber; pnumber = new int; first line of code declares a pointer PNUMBER, the second line of code assigns an integer space, and makes PNumber points to this section Allocated memory. Below is another example, this time uses a Double: double * PDOUBLE; PDOUBLE = New Double; these rules are the same T, so you should be able to master it easily. Dynamic allocation and local variables are: The memory you allocate does not be released when the function returns and the statement block ends, so if you use dynamic allocation to rewrite the above code, then it will work properly: #include int * ppoint; void somefunction () {// causes PPOINTER to point to a new integer PPOINTER = new int; * ppointer = 25;} void main () {somefunction (); // Let PPointer point Some stuff Printf ("Value of * PPointer:% D / N", * ppointer);} Please read and compile the above sample code, and be confident that you have already understood why it works. When the SomeFunction is called, it assigns a memory and causes PPointer to point to this memory. This time when the function returns, this new memory will keep it well, so PPointer still points to some useful content. This is dynamic allocation! Be sure that you have already understood this, then continue to read a serious mistake in this code.

I have to understand, I understand

There is also a complicated factor and is very serious - although it is very remedied. The problem is that it is still intact when you assign, although it is still intact, this memory will never be destroyed automatically. That is to say, if you don't inform the computer ending, this memory will always exist, the result of this is the waste of memory. In the end, the system will crash because of memory consumption. So this is a quite important issue. When you use the memory, release its code very simple: delete ppoint; it is so simple. Anyway, in your passing a valid pointer - is also a pointing, you have already assigned a good memory pointer, not the old garbage memory - time, you need to be very careful. Try DELETE Solid memory is very dangerous, which may cause your program to crash. Ok, the following is that example, this time it doesn't waste memory: #include int * ppointer; void SomeFunction () {// Point PPointer points to a new integer PPOINTER = new int; * PPOINTER = 25;} void main () {somefunction (); // Let PPointer point to some stuff ("Value of * Ppoint:% D / N", * ppointer; delete ppoint;} The only one line is also different The most essential point. If you don't drop the memory Delete, your program will get a "memory leak". If memory leaks appear, then unless you shut down the application, you will not be able to reuse this leak memory. Pass the pointer to the function

It is very useful to pass the technique of the function to the function, but it is easy to master (translation: Is there a inevitable turning relationship? Hey, I can't see it, but since the author wrote, I can't find a suitable correlation word, I have Translate by literally). If we want to write a program, you have to increase a number of 5, we may write: #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, this program addFive Number is a copy of NMYNumber that is passed to this function, not NMYNumber itself. Therefore, "Number = NUMBER 5" is the line with this copy, and the original variable in main () does not change. You can run this program to try to prove this. For this program, we can pass the plot of this digital memory address to the function. In this way, we need to modify this function so that it can receive a pointer to integer. So, we can add an asterisk, which is changed "Void AddFive (int * number)". Here is this modified program, not to pass the NMYNumber address (not it itself) passed the past? Here, the change is to add a "&" symbol, which reads (you should recall) "The address of (..." 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);} You can try to write a program to prove this. Note the importance of "*" before Number in the AddFive function? That is to tell the compiler we have to add 5 on the numbers pointed to by the pointer Number, not to the pointer itself plus 5. The last thing you should pay attention to, you can also return to the pointer in the function, like this: int * myfunction (); in this example, MyFunction returns a pointer to integers. Pointer pointer

With regard to pointers, I still have two points to remind you. One of them is a pointer to the structure or class. You can define a class: class myclass {public: int m_number; char m_character;}; then you can define a Myclass variable: myclass think; you should already know these, if you haven't, you need to read it Information in this regard. You can define a pointer to myclass: Myclass * Thing; just like you expect. Then you can assign some memory for this pointer: Thing = new myclass; this is the problem. How will you use this pointer? Hey, usually you will write: "Thing.m_Number", but for this example, because Thing is not a MyClass, but a pointer to myclass, so it does not contain a variable named "m_number"; it The pointer to the structure contains this m_number. Therefore, we must use a different conversion method. This is to replace "." (Point) to a "->" (horizontal line and a larger number). Please see the following 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 Point of PPOINTER;} Pointer to array

You can also make the pointer to the array, as follows: int * parray; parray = new int [6]; this will create a pointer PARRY, which will point to an array of 6 elements. Another way to use dynamic allocation is as follows: int * parray; int myArray [6]; parray = & myarray [0]; Please note that you can write only MyArray instead & myarray [0]. Of course, this approach is only applicable to arrays, which is the implementation of the C / C language (the translation: You can also assign the function name to a corresponding function pointer). The usual error is written as "parray = & myarray;", this is incorrect. If you write this, you will get a pointer to the array pointer (maybe some mouths?), This is of course not what you want.

Use pointer to array

If you have a pointer to an array, how will you use it? Hey, if you say, you have a pointer to an array of integers. This pointer will initially point to the first value of the array, look at the following example: #include void main () {int Array [3]; array [0] = 10; array [1] = 20; Array [2] = 30; INT * PARRAY; PARRAY = & Array [0]; Printf ("Parray Points to the Value% D / N", * PARRAY);} To move the pointer to the next value of the array, we You can use PARRAY . We can also - Of course, some people may also guess - using PARRAY 2, which will move this array pointer to two elements. It should be noted that you must clear what the upload of the array is (3), because when you use a pointer, the compiler cannot check if you have moved out of the end of the array. So, you may easily crash the system. The following is still this example showing the three values ​​we set: #include void main () {int Array [3]; array [0] = 10; array [1] = 20; array [ 2] = 30; INT * PARRAY; PARRAY = & array [0]; Printf ("PARRAY POINTS to the VALUE% D / N", * PARRAY); PARRAY ; Printf ("Parray Points to the value% D / N", * Parray); Parray ; Printf ("Parray Points to the value% D / N", * parray);}, you can minus the value, so Parray - 2 is the first two elements of the Parray current location. However, make sure you are operating pointers instead of operating the value it pointing. This use of pointers is very useful when cycling, such as for or while loops. Please note that if you have a pointer (for example, int * pnumberset), you can also see it as an array. For example, PNumBerset [0] is equivalent to * pNumberSet, PNumBerset [1] is equivalent to * (PNumBerset 1). About arrays, I also have the last warning. If you use new to allocate space, just like this: int * parray; parray = new int [6]; then you must release it: delete [] PARRAY; Please note that DELETE is after []. This is informing the compiler that it is deleting an array, not a separate project. You must use this method when you use an array, otherwise a memory leak may be obtained. Last words

Finally, you should pay attention to: You can't delete the memory that is not allocated with new, like this: void main () {int number; int * pnumber = number; delete pnumber; // error: * PNumber is not using new assignment of}

Frequently Asked Questions and FAQ

Q: Why get "SMBOL undefined" error when using New and Delete? A: This is probably because your source file is explained by the compiler as a C file because the New and Delete operators are new features of C . The usual correction method is to use .cpp as your source file extension. Q: What is the difference between NEW and Malloc? A: New is a C unique keyword, and is a standard allocated memory method (except for the memory allocation method of the Windows program). You must never use Malloc in a C C program unless absolutely necessary. Since Malloc is not an object-oriented characteristic design, use it to assign memory for class objects, which will not call the class constructor, which will have problems. For these reasons, this article does not discuss them, and as long as it is possible, I will also avoid using them.

Q: Can I use free and delete? A: You should use and allocate the memory matching method to release memory. For example, using free to release memory allocated by malloc, use Delete to release memory allocated by the NEW.

Quote

From a certain point of view, the reference has exceeded the scope of this article. However, since many readers have asked me in this, I will conduct a brief discussion here. Quote and pointers are very similar, which can be used in many cases. If you can recall the contents of the above - I mentioned "&" Read as "The Address of (... The address)", in the declaration of the exception. In this case, it should read "A Reference to (... reference)", as follows: int & number = myothernumber; Number = 25; reference is like a pointer to my myothernumber, but it is an automatic analysis The address, so its behavior is like the actual value pointed to by the pointer. The pointer code with its equivalent is as follows: int * pNumber = & myothernumber; * pNumber = 25; another difference between the pointer and reference is that you cannot replace the content, that is, you can't replace the reference points after the declaration. For example, the following code will output 20: int myfirstnumber = 25; int myReference = MyfirstNumber; myreference = mysecondNumber; Printf ("% d", myfristnumber); When in the class, the reference value must be Constructor settings, like this: CMYCLASS :: CMYCLASS (int & variable): m_myreferenceincmyclass (variable) {// Here is constructor}

to sum up

This subject is originally difficult to master, so you'd better read it at least twice - because most people can't understand immediately. Let me list this paper below:

1. The pointer is a variable that points to a location in memory, you can define a pointer (iNT * Number) by adding an asterisk (*) before the variable name (*). 2, you can get its memory address by adding "&" in the variable name (which is pnumr = & my_number). 3. In addition to the statement (for example int * number), the asterisk should read "The Memory Location Pointed to by" The Memory Position Pointing by ... ". 4. In addition to in the statement (such as int & number), "&" should read "The Address of (...". " 5, you can use the "New" key to allocate memory. 6, the pointer must match the variable type it points to, so INT * NUMBER should not point to a MyClass. 7, you can pass pointers to the function. 8, you must use the "delete" keyword to release the memory you assigned. 9. You can use & Array [0] to get a array of pointers. 10, you must use delete [] to release the array of dynamic assignments, not simple delete. This is not a complete pointer guide, one thing I can involve other details, such as pointers of pointers; there are some things that I have not involved, such as function pointers - I think as beginners, this Some are more complicated; there are some things that are rarely used, I have not mentioned here, provision of these un practical details make everyone confusing.

That's all! You can try to run the program in this article and write some examples to understand the problem about the pointer.

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

New Post(0)