Pointer Guide

zhaozj2021-02-16  46

Translator's order: This is the best entry-level article I have ever seen about the pointer, which allows beginners to master complex pointer operations in a short period of time. Although, now Java, C #, etc. has canceled pointers, but as a C programmer, the direct operating memory of the pointer, has the advantages of fast, saving memory in data operation, still a lot of C programmers's favorite . The pointer is like a good sword, just see how you apply it! Technical issues related to this article You can write to me: Webmaster@chinahai.com. At the same time, two related articles "template Guide" and "STL Guide" is also completed, I hope to help you! Loading ... Translator: What is a pointer? In fact, the pointer is like other variables, and the difference is that the general variables contain actual real data, and the pointer is an indicator that tells the program to find data in the area where the memory can be found. This is a very important concept, and many programs and algorithms are designed around the pointer, such as a list. Start learning how to define a pointer? Just like you define a different variable, just add an asterisk before the pointer name. Let's take an example: Below this program defines two pointers, they all point to integer data. INT * pNumberone; int * pnumbertwo; Do you notice the "P" prefix before the two variables? This is a habit of programmers to define pointers to increase the reading of the programs, indicating that this is a pointer. Now let's initialize these two pointers: pnumberone = & some_number; pnumbertwo = & some_other_number; & Some Address ", it indicates that the address returned is the value of the variable in memory instead of the value of the variable itself. In this example, PNumberone is equal to the address of Some_Number, so now PNumberone points to Some_Number. If we now use some_number in the program, we can use pNumberone. Let's learn an example: In this example you will learn there, if you don't understand the concept of pointers, I suggest you look more about this example, the pointer is a very complicated thing, but you will be very happy. its. This example is used to enhance your understanding of the content described above.

It is written in c (Note: The original English version is written with C, the translator re-writes all the code again, and compiled all the code in DEV C and VC !) #Include void main () {// declared variable: int nNumber; Int * ppoint; // now assigns them: nNumber = 15; ppointer = & nnumber; // Print Variable NNumber: cout << "nnumber is equal to:" < int * ppoint; void somfunction (); {int nNumber; nNumber = 25; // Let the pointer points to nNumber: ppoint = & nnumber;} void main () {someFunction (); / / for ppointer assignment / / Why didn't you get a 25 cout << "value of * ppoint: << * ppoint << Endl;} This program first calls the SomeFunction function, creating a variable called nNumber, then let the pointer PPointer points to it. But where is the problem? When the function is over, NNumber is deleted because this part variable. Local variables are automatically deleted by the system after defining its function. That is to say, when the SomeFunction function returns the main function main (), this variable has been deleted, but the PPointer also points to the area used by the variable, but now is not part of this program. If you still don't understand, you can read this program, pay attention to its local variables and global variables, which are very important. But how can this problem solved? The answer is dynamic allocation technology. Note that this is different in C and C . Since most of the programmers use C , I use the title of C . Dynamic allocation dynamic allocation is a key technique for pointers. It is used to allocate memory and make pointers to point to them without having to define variables. Although this may make you confused, it is really simple. The following code is an example of allocating memory for a integer data: int * pNumber; pNumber = new int; first line declares a pointer PNUMBER. The second behavior allocates a memory space and let PNumber points to this new memory space.

Below is a new example, this time is Double Double Prefare: Double * PDOUBLE; PDOUBLE = New Double; this format is a rule, which is not wrong. But what is the difference between dynamic allocation and the previous example? That is, when the function returns or executed, the memory area you assigned is not deleted, so we can now use dynamic allocation to rewrite the above program: #include int * ppoint; void somefunction () {// Let the pointer points to a new integer ppoint = new int; * ppoint = 25;} void main () {someFunction (); // For the PPOINTER assignment cout << "value of * ppointer: << * PPointer << Endl;} Read this program, compile and run it, be sure to understand how it works. When the SomeFunction is called, it assigns a memory and let PPointer point to it. This time, when the function returns, the new memory area is retained, so PPointer always refers to useful information because of dynamic allocation. But you carefully read this program, although it gets the right result, there is still a serious mistake. Assigned memory, don't forget to recycle too complicated, how can there be a serious mistake! In fact, it is not difficult to correct it. The problem is: You dynamically assign a memory space, but it will never be automatically deleted. That is, this memory space will always exist until you tell your computer that you have already used. As a result, you didn't tell the computer that you no longer need this memory space, so it will continue to occupy a waste of memory, and even your program is running, other programs are running. It still exists. When such problems accumulate to a certain extent, it will eventually cause the system to crash. So this is very important, after you run it, please release its space, such as: delete ppoint; this is almost, you have to be careful. At this time you have terminated an effective pointer (a pointer that does point to a memory). The following program does not waste any memory: #include int * ppoint; void SomeFunction () {// Let the pointer points to a new integer ppoint = new int; * ppoint = 25;} Void Main () {someFunction (); // For PPointer assignment cout << "value of * ppoint: << * ppoint << endl; delete ppoint;} Only one line is different from the previous program, but this is the last line very important. If you don't delete it, you will create "memory vulnerability", and make memory gradually leak. (Translator: If you call two SomeFunction twice in the program, how do you modify this program? Please think about itself) Pass your pointer to function to transfer pointer to function is very useful, it is easy to master.

If we write a program, let a number plus 5, look at this program is complete? : #Include Void AddFive (int Number) {Number = Number 5;} void main () {int nmynumber = 18; cout << "My Original Number IS" << nmynumber << Endl; addfive nmynumber); cout << "My new number is" << nmynumber << endl; // Get the result 23? Where is the problem? } The problem is transmitted to the function in a copy of the number of variable NMYNumber, not the variable itself in the number of Number used in the function AddFive. Therefore, "Number = NUMBER 5" is the line plus a copy of the variable 5, and the original variable is still unchanged in the main function main (). Try to run this procedure and take yourself. To solve this problem, we will pass a pointer to the function, so we have to modify the function to accept the pointer: change the 'Void AddFive (int * number)'. Below is the changed program, pay attention to the function call to use the & number to indicate that the pointer is pointer: #include void addfive (int * number) {* Number = * Number 5;} void main () {Int nmynumber = 18; cout << "My Original Number IS" << nmynumber << endl; addfive (& nmynumber); cout << "My new number is" << nmynumber << Endl;} Try yourself to run it Note that the importance of the function addFive's parameter Number is added: it tells the compiler, we add the variable referred to by the pointer 5. And don't do it yourself. Finally, if you want the function to return a pointer, you can write: int * myfunction (); in this sentence, MyFunction returns a pointer to the integer. Pointing to class pointer pointers in the class should be careful, you can define a class as follows: class myclass {public: int m_number; char m_character;}; then you can define a MYCLASS class variable: Myclass You should already know how to define a pointer: Myclass * Thing; then you can assign a memory space to it: Thing = new myclass; note, the problem has appeared. How do you plan to use this pointer, usually you might write 'thing.m_number', but thing is a class, no, it is a pointer to the class, which does not contain a variable called M_Number.

So we must use another method: That is to change '.' (Point number) to ->, come and see the example below: Class myclass {public: int m_number; char m_character;}; void main () {Myclass * PPointer PPOINTER = new myclass; ppointr-> m_number = 10; ppointer-> m_character = 's'; delete ppoint;} Pointer to array You can also make pole points to an array, follow the method: int * parray; parray = New Int [6]; the program creates a pointer PARRAY to point to an array with six elements. Another method, no dynamic allocation: int * parray; int myArray [6]; parray = & myarray [0]; note, & myArray [0] can also be short-neuttered as MyArray, which is expressed as the first element address of the array. But if Parray = & MyArray may have problems, the result is that PARRAY points to point to the array pointer (although it is equal to & myArray [0]) instead of what you want, it is easy in the multidimensional array. Error. Using a pointer in an array Once you have defined a pointer to an array, how do you use it? Let's take an example, a pointer to the integer array: #include void main () {int Array [3]; array [0] = 10; array [1] = 20; array [2 ] = 30; INT * PARRAY; PARRAY = & array [0]; cout << "PARRAY POINTS to the value% d / n" << * parray << Endl;} If the pointer points to the next one in array elements, With PARRAY . You can also use the PARRAY 1 you should be able to think of Parray 1, will make the pointer to the next element of the array. It should be noted that when you move your pointer, the program does not check if you have moved beyond your defined array, that is, you are likely to access data outside the array through the simple pointer of the above, and the result is It may cause the system to crash, so please be careful. Of course, Parray 1 can also be PARRAY - 1, which is often used in the cycle, especially in the While cycle. Another thing to note is that if you define a pointer pointing to the integer: int * pNumberSet, you can treat it as an array, such as: pnumberset [0] and * pnumberset is equal, PNumBerset [1] * (PNumberSet 1) is also equal. The last one warning in this section: If you use New to dynamically allocate an array, int * parray; parray = new int [6]; don't forget to recycle, delete [] PARRY; this sentence is tell the compiler is Delete the entire array without a separate element. Ten thousand remembered.

There is still a little care, don't delete a pointer that all assigns a memory, typically if you don't have a new allocation, don't use delete: void main () {int number; int * pnumber = number; delete pnumber; // Error - * PNumber does not use new dynamic allocation of memory.} Frequently Asked Questions Q: Why is I always appear in the new and delete statements when I compiler? A: New and Delete are extensions in C in C, this error is that the compiler thinks that your current program is C without C , of course it will be wrong. See if your file name is. CPP. Q: What is the difference between NEW and MalloC? A: NEW is a criteria for C to allocate a standard function of memory. If there is no need, please do not use Malloc in C . Because Malloc is the syntax in C, it is not designed for object-oriented C . Q: Can I use free and delete at the same time? A: You should note that their respective matches are different. Free is only used in memory operations allocated with MalloC, while Delete is only used in memory operations allocated with the New. Quote (Write to some capable readers) This section is not the center of this article, just for some capable readers. Some readers often ask me questions about the reference and pointer, here I briefly discuss it. In the learning of the front pointer, we know (&) Is reading "What is the address", but in the following program, it is read "Int & number = myothernumber; Number = 25; reference is a bit like A pointer to my myothernumber, is different, it is automatically deleted. So he is more useful than a pointer in some occasions. The code with the above equivalent is: int * pNumber = & myothernumber; * pNumber = 25; pointer and reference to another difference, you can't modify you have defined a reference, that is, you can't change its content when it is declared. . For example: int myfirstnumber = 25; int mysecondNumber = 20; int & myreference = myfirstnumber; myreference = mysecondNumber; // Can this step change myReference? Cout << myfristnumber << Endl; // The result is 20 or 25? When operating in the class, the reference value must be set in the constructor, an example: CMYCLASS :: CMYCLASS (INT & VARIABLE): M_MyReferenceIncMyClass (variable) {// constructor code here} Summary This article will be more difficult to master Therefore, it is best to read more. Some readers are still can't understand, here I will make a brief summary: The pointer is a variable pointing to the memory area, and when the variable is preceded in the variable (eg int * number).

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

New Post(0)