Get started with C + + pointer pointer reprint

Source: Internet
Author: User

This is the best entry-level article I've ever seen on pointers, which allows beginners to master complex pointer manipulations in a very short period of time. Although, now the Java, C # and other languages have been canceled pointers, but as a C + + programmer, Pointer direct operation of memory, in the data operation has a fast speed, save memory and other advantages, is still a lot of C + + Programmer's favorite. The pointer is like a good sword, it depends on how you apply it!
 
What is a pointer?
In fact, the pointer is like other variables, the difference is that the general variable contains the actual real data, and the pointer is an indicator, it tells the program in which area of the memory to find the data. This is a very important concept, and there are many programs and algorithms that are designed around pointers, such as linked lists.
Start learning
How do you define a pointer? Just as you define a different variable, just add an asterisk to the pointer's name. Let's look at an example:
The following program defines two pointers, all of which point to integer data.
int* Pnumberone;
int* Pnumbertwo;
Did you notice the "p" prefix in front of the two variable names? This is a habit that programmers typically use when defining pointers, to improve the reading of the program, and to indicate that this is a pointer. Now let's initialize both of these pointers:
Pnumberone = &some_number;
Pnumbertwo = &some_other_number;
The & reads "What's the address", which means that the value returned is the address of the variable in memory instead of the variable itself. In this example, Pnumberone equals Some_number's address, so now pnumberone points to some_number. If we are going to use Some_number in our program now, we can use Pnumberone.
Let's learn an example:
In this example you will learn a lot, if you do not understand the concept of pointers, I suggest you look at this example more than a few times, the pointer is a very complex thing, but you will soon master it.
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 in C code, the translator rewrite the C + + write all the code, and in the dev C + + and VC + + compiled through!) )
#include <iostream.h>
void Main ()
{
Declaring variables:
int nnumber;
int *ppointer;
Now assign them values:
Nnumber = 15;
Ppointer = &nNumber;
Print out the value of the variable Nnumber:
cout<< "Nnumber is equal to:" << nnumber<<endl;
Now change the value of the Nnumber by the pointer:
*ppointer = 25;
Prove that Nnumber has been changed by the above procedure.
Re-print the value of the Nnumber:
cout<< "Nnumber is equal to:" <<nNumber<<endl;
}
Read through the program, compile and run it, and be sure to understand how it works. If you're done, get ready and start the next section.
Trap!
Try, can you find out the error of this program?
#include <iostream.h>
int *ppointer;
void SomeFunction ();
{
int nnumber;
Nnumber = 25;
To point the pointer to Nnumber:
Ppointer = &nNumber;
}
void Main ()
{
SomeFunction (); Assigning Values to Ppointer
Why did it fail here? Why didn't you get 25
cout<< "Value of *ppointer:" <<*pPointer<<endl;
}
This program calls the Somefunction function first, creates a variable called Nnumber, and then lets the pointer ppointer point to it. But where is the problem? When the function is finished, Nnumber is deleted because of this local variable. A local variable is automatically deleted by the system after the function that defines it is executed. That is, when the Somefunction function returns the main function main (), the variable has been deleted, but Ppointer also points to the area where the variable was used but is not currently part of the program. If you don't understand it, you can read the program again, notice its local variables and global variables, and these concepts are all very important.
But how to solve this problem? The answer is dynamic allocation techniques. Note that this is different in C and C + +. Since most programmers are using C + +, I use the usual appellation in C + +.
Dynamic allocation
Dynamic allocation is a key technique of pointers. It is used to allocate memory without having to define variables and let the pointer point to them. Although that might confuse you, it's really simple. The following code is an example of allocating memory for an integral type of data:
int *pnumber;
Pnumber = new int;
The first line declares a pointer pnumber. The second behavior an integer data allocates a memory space and lets Pnumber point to this new memory space. Here is a new example, this time with double-precision type:
Double *pdouble;
pdouble = new Double;
This format is a rule, so it is not wrong to write you.
But what is the difference between dynamic allocation and the previous example? That is, when the function returns or executes, the area of memory that you allocate is not deleted, so we can now rewrite the above program with dynamic allocation:
#include <iostream.h>
int *ppointer;
void SomeFunction ()
{
Let the pointer point to a new integral type
Ppointer = new int;
*ppointer = 25;
}
void Main ()
{
SomeFunction (); Assigning Values to Ppointer
cout<< "Value of *ppointer:" <<*pPointer<<endl;
}
Read through the program, compile and run it, and be sure to understand how it works. When Somefunction is called, it allocates a memory and lets Ppointer point to it. This time, when the function returns, the new memory area is preserved, so ppointer always points to useful information because of the dynamic allocation. But you read the above program carefully, although it got the correct result, there is still a serious error.
Allocate memory, don't forget to recycle
Too complicated, how can there be a serious mistake! In fact, it is not difficult to correct. The problem is that you dynamically allocate a memory space, but it is never automatically deleted. In other words, this memory space will persist until you tell the computer that you have finished using it. As a result, you have not told the computer that you no longer need this memory space, so it will continue to occupy the memory space to cause waste, even your program run, other programs run it still exists. When such problems accumulate to a certain extent, it will eventually cause the system to crash. So it is important that after you run out of it, please release its space, such as:
Delete Ppointer;
That's almost it, you have to be careful. In this you terminate a valid pointer (a pointer that does point to some memory).
The following program, it does not waste any memory:
#include <iostream.h>
int *ppointer;
void SomeFunction ()
{
Let the pointer point to a new integral type
Ppointer = new int;
*ppointer = 25;
}
void Main ()
{
SomeFunction (); Assigning Values to Ppointer
cout<< "Value of *ppointer:" <<*pPointer<<endl;
Delete Ppointer;
}
Only one line is different from the previous, but this last line is very important. If you do not delete it, you will create a "memory leak" and let the memory gradually leak.
(Translator: If you call two times in the program somefunction, how can you modify this program?) Ask the reader to think for themselves)
Passing pointers to functions
Passing pointers to functions is very useful and easy to master. If we write a program, let a number plus 5, take a look at this program complete? :
#include <iostream.h>
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;
Did you get the result 23? Where is the problem?
}
The problem is that the number used in the function addfive is a copy of the variable Nmynumber and is passed to the function, not the variable itself. Therefore, "number = number + 5" is the line that adds a copy of the variable to 5, and the original variable remains unchanged in main function main (). Try to run the program and experience it yourself.
To solve this problem, we're going to pass a pointer to the function, so we're going to modify the function so that it can accept the pointer: change ' void addfive (int number) ' to ' void addfive (int* number) '. The following is the changed program, note that the function calls to use the code, to indicate that the pointer is passed:
#include <iostream.h>
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 to run it yourself, notice the importance of adding the * number before the argument of the function addfive: it tells the compiler that we are adding 5 to the variable that the pointer refers to. Instead of the pointer you add 5.
Finally, if you want to have the function return a pointer, you can write this:
int * MyFunction ();
In this sentence, MyFunction returns a pointer to an integral type.
Pointers to classes
Pointers operate in classes with extra care, you can define a class in the following ways:
Class MyClass
{
Public
int m_number;
Char M_character;
};
Then you can define a variable for the MyClass class:
MyClass thing;
You should already know how to define a pointer:
MyClass *thing;
Then you can allocate a memory space to it:
thing = new MyClass;
Note that the problem has arisen. How do you intend to use this pointer, usually you may write ' thing.m_number ', but thing is a class, no, it is a pointer to a class, which itself does not contain a variable called M_number. So we have to use a different approach: just put '. ' (point number), see the following example:
Class MyClass
{
Public
int m_number;
Char M_character;
};
void Main ()
{
MyClass *ppointer;
Ppointer = new MyClass;
Ppointer->m_number = 10;
Ppointer->m_character = ' s ';
Delete Ppointer;
}
Pointer to array
You can also point the pointer to an array and follow the instructions below:
int *parray;
Parray = new Int[6];
The program creates a pointer Parray, which points to an array of six elements. Another method, without dynamic allocation:
int *parray;
int myarray[6];
Parray = &MyArray[0];
Note that &myarray[0] can also be abbreviated to MyArray, which means the address of the first element of the array. But if written parray = &myarray may be problematic, the result is that Parray points to pointers to arrays (although in a one-dimensional array, even though they are equal to &myarray[0], rather than what you want, it is easy to make mistakes in multidimensional arrays.
Using pointers in arrays
Once you have defined a pointer to an array, how do you use it? Let's take a look at an example, a pointer to an array of integers:
#include <iostream.h>
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 you have the pointer pointing to the next in the array element, you can use parray++. You can also use Parray + 1, which you should think of, to point the pointer to the next element of the array. It is important to note that when you move the pointer, the program does not check whether you have moved beyond the array you have defined, that is, you are likely to access the data outside the array through the simple pointer plus operation above, and the result is that the system may crash, so be careful.
Of course there are Parray + 1, there can also be pArray-1, this operation is very common in the loop, especially in the while loop.
Another point to note is that if you define a pointer to an integer number: int* Pnumberset, you can think of it as an array, such as: pnumberset[0] and *pnumberset are equal, pnumberset[1] and * ( Pnumberset + 1) are also equal.
A warning at the end of this section: If you dynamically allocate an array with new,
int *parray;
Parray = new Int[6];
Don't forget to recycle,
Delete[] Parray;
This is the word that tells the compiler to delete the entire array without a single element. Never mind.
Something
Also, be careful not to delete a pointer that does not have memory allocated at all, typically if you do not use the new assignment, then delete:
void Main ()
{
int number;
int *pnumber = number;
Delete Pnumber; Error-*pnumber does not dynamically allocate memory with new.
}
Frequently Asked Questions
Q: Why do I always have a ' symbol undefined ' error in the new and DELETE statements when I compile my program?
A:new and delete are all extensions to C + +, and this error is that the compiler thinks that your current program is C and not C + +, of course it will be wrong. See if your file name is. cpp end.
What is the difference between q:new and malloc?
A:new is the key word in C + +, a standard function for allocating memory. If it is not necessary, 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 both free and delete?
A: You should be aware that they each match the same operation. Free is used only in memory operations allocated with malloc, and delete is used only in memory operations allocated with new.
Citation (to some capable reader)
The content of this section is not the center of my article, but it is for some readers who have the ability to refer to it.
Some readers often ask me questions about references and pointers, and here I briefly discuss them.
In the previous pointer learning, we know (&) is read as "what address", but in the following program, it is read as "What kind of reference"
int& number = Myothernumber;
Number = 25;
The reference is a bit like a pointer to Myothernumber, but the difference is that it is automatically deleted. So he is more useful than a pointer on some occasions. The code equivalent to the above is:
int* Pnumber = &myOtherNumber;
*pnumber = 25;
Another difference between a pointer and a reference is that you cannot modify a reference that you have already defined, meaning that you cannot change what it refers to when it is declared. As an example:
int myfirstnumber = 25;
int mysecondnumber = 20;
int &myreference = Myfirstnumber;
Myreference = mysecondnumber;//Does this step make the myreference change?
cout<<myfristnumber<<endl;//The result is 20 or 25?
When working in a class, the referenced value must be set in the constructor, for example:
Cmyclass::cmyclass (int &variable): m_myreferenceincmyclass (variable)
{
Constructor code here
}
Summarize
This article may be difficult to master at first, so it is better to read it more than once. Some readers do not understand for the time being, here I will make a brief summary:
The pointer is a variable that points to the memory area, with an asterisk (*) in front of the variable name (for example, int *number).
You can get the address of any one variable, just precede the variable name with the & (for example: Pnumber = &my_number).
You can dynamically allocate memory with the ' new ' keyword. The type of the pointer must be the same as the variable type it refers to (for example, int *number cannot point to MyClass).
You can pass a pointer to a function. You must delete your dynamically allocated memory with ' delete '.
You can use &array[0] to point the pointer to an array.
You must use delete[] instead of Delete to delete the dynamically allocated array.
The article is almost over here, but these are not pointers to everything, like pointers to pointers and so on I haven't introduced, because these things are too complicated for a beginner pointer, I can't let the reader start to be too complicated to scare away. OK, come here, try to run the small program I wrote above, but also to write their own programs, you will certainly progress is not small!

Get started with C + + pointer pointer reprint

Related Article

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.