C ++ getting started (2) -- Exploring the pointer (I)

Source: Internet
Author: User

It seems that from the age of C, pointer has become a difficult point in the minds of the masses. In today's c ++, the complexity of object-oriented, template, and other technologies has reduced the difficulty of learning the basic process-oriented part of C in the past, but the pointer content still occupies the "difficult area. The reason may be that a considerable number of C/C ++ languages have been transferred from "advanced" languages such as basic, even learning from scratch and having little programming experience before. Pointers belong to one of the most "low-level" components in C/C ++, and they are also the main scenes with many tricks, beginners who have no knowledge of the underlying layer may be dizzy when they pass this notebook, which is inevitable. In this section, we will try to start with some basic underlying principles. Well, I hope it will be helpful to you.

0. First talk about variables
0. Talk about variable

Ah, variables are a friendly concept. In most advanced languages, a variable is an identifier consisting of letters and some allowed symbols (numbers, underscores, etc.). It can record useful data for us, and can be involved in operations, re-assignment ...... Well, it's an old friend. But if you want to learn C ++, you must have a deeper understanding of this old friend. Let's start with the declaration of variables. For example, we write:

Int main ()
{
Int;
//...
Return 0;
}

Obviously, in the first line of the main program, we declare and define an integer variable A. When the system (the compiler) sees this line, two things will be done: 1. allocate a small block of memory that can be used to hold integer values for storage variable A; 2. secretly remember the first address of the memory. In the future, as long as your program uses a, the system will find the memory through the address value, perform the operations as required ...... Memory, You know, memory is divided into many storage units, just like every household in the city, each unit (household) has a unique number called the address value (house number) unlike other units, to access a specific unit (check the account), you need to index (visit) the address value (house number ).
Sorry, so far, these operations have been secretly done by the system, so we can easily write simple and clear programs. However, if we are curious, we can check whether C ++ is allowed. For example, to view the address value of A, you can use the value operator &. You only need to add & before the variable to get its address:

# Include <iostream>

Using namespace STD;

Int main ()
{
Int;
A = 3;
Cout <"A =" <A <'/N'; // The first information associated with the variable: the value of the Variable
Cout <"address of a:" <& A <Endl; // The second information associated with the variable:
// Address value
Return 0;
}

The following figure shows the output on my machine:

A = 3
Address of A: 0x241ff5c

There should be no problem with the output of a = 3, but address of a, different machines, or even the same machine, will be different at different times, which is easy to understand: after all, the memory layout changes from time to time. The system allocates a space for you. If you can use it, do not be too picky. Also, is "0x241ff5c" Strange? This is because the default hexadecimal format is used for the output of the address, so it looks very mysterious. In fact, there is only an integer in it. You can see that it is not pleasing to the eye to use decimal output, when it comes to the format operator of the output stream, I will not talk much about it here (I will check it myself ).
Now, we can understand the specific storage address of any variable (or object) after this section. In turn, if we know the address of a variable, how can we perform variable-type operations on it in turn? The answer is to use the "*" operator. Like the "&" operator, it is added before an address value, and we get the variable corresponding to this address. This process is usually calledDereference), "*" Is the unreferencing OPERATOR:

# Include <iostream>

Using namespace STD;

Int main ()
{
Int;
A = 3;
Cout <"A =" <A <'/N'; // same as before ......
Cout <"address of a:" <& A <'/N'; // same as before ......
Cout <"get back :";
Cout <* (& A) <'/N'; // use & A to obtain the address of a, and then use * to return the address to variable.
* (& A) = 5; // Similarly, variables returned by * can be routinely operated like the original variable
Cout <"now, A =" <A <Endl; // verify whether a actually changes
Return 0;
}

The output result of this funny program is as follows (similarly, the address value is only a possible version ):

A = 3
Address of A: 0x241ff5c
Get Back A: 3
Now, a = 5

The reason why it is funny is that we first use the address operator to retrieve the address of a, and then use the anti-reference operator to return the address to, in actual development, it is unlikely that such a direct curve will save the country. However, this funny program really makes us understand that the value operator and the anti-reference operator * are opposite to each other. The former gets its address from the variable, the latter obtains the corresponding variable from the address. If both applications are applied at the same time, that is, * (& A) in the program, then we finally have to go back to.

1. Finger needle
1. pointer

Now we know the new numeric type in C ++: address value, which is the same as integer, floating point type, double precision type, complex type, and so on, most of the time, it is hidden behind the programming language. We also know that values such as integer and floating-point types store integer variables, constants, and floating-point variables and constants, can the address value be stored with corresponding variables/constants? The answer is yes. The variable used to store the address value in C/C ++ is called a pointer variable/constant. This is an image-like saying: The address value of pointer storage usually refers to a specific bucket. With pointer guidance, we can access the corresponding volume; in addition, the addresses stored in Pointer variables can be changed through variable assignment, which makes the pointer quite flexible. In addition, dynamic memory allocation is also inseparable from pointers ...... These are all future content. Well, let's take a look at how to declare pointer variables.
For integer variables, we use the int keyword to modify them when declaring them, as shown in figure

Int;
Declared an integer variable named A. Since a is modified by INT, A has the attributes of the int type variable: for example, it supports addition, subtraction, multiplication, division (instead of division), assignment, and other operations. If I add a few characters, it will become:
Int A, * P;
What does that mean? Based on the above ideas, we will give you five seconds to think: 1, 2, 3, 4, 5! Okay. You can say that we declare two integer types: A and * P. They all support addition, subtraction, multiplication, and Division (instead of Division), assignment, and other operations ...... * P and A should beEquivalentThey should be okay.RepresentativeAn integer variable. That's good. It's inferred from our own understanding. Now let's look at it again: Since * P can represent an integer variable, so what should p mean by removing?
Do you still remember the magical relationship & with * mentioned above? They provide the opposite function: Add and get the address of the variable, and add * to the address to get the corresponding variable. Now, the reverse expression of the preceding sentence is changed to: remove the preceding & from the address and return the corresponding variable (for example, change & A back to ), if you remove * from a variable, the return address is obtained. (as mentioned above, * (& A) is equivalent to variable A. If you remove * and change * To & A, the return address of a is obtained ).
Well, we know that * P can represent an integer variable, so removing *'s p represents the * P address, that is, p represents an address!
Now, we can understand why we declare a pointer with the "*" sign instead of the "&" sign or something else. Now there is a problem: the Declaration (Definition) variable will have the corresponding memory allocation, for example, the system will see int A; will allocate block memory for a. In this case, for the statement int, * P; it seems that both A and * P will be allocated with a memory that stores integers.
Oh, unfortunately, our logic didn't take it for granted. For C/C ++, int, * P will enable the system to allocate an integer memory for a (without a doubt), but for * P, because * is an operator, it only serves as an identifier, therefore, the system only focuses on the identifier P, which will allocate memory for P instead of * P. Well, repeat it again: * It only helps the system understand the position of P. In any declaration (Definition), the system finally allocates only the identifier to it, so P will eventually get its memory.
What kind of memory does P get? Since * P can represent int-type variables, we have just analyzed that p represents the address value for marking an int-type variable. To connect them, it is: the memory obtained by P is used to store the address value indicating an int variable -- p is a variable that stores an integer address -- oh, p is the pointer variable we previously imagined! Haha, I tried my best to get you!


Well, the General C ++ tutorials directly introduce the declaration of pointers, and we basically use logical reasoning to export the declaration method step by step based on the basics in section 0th, this kind of learning may help us grasp the essence of language at a more detailed level. This chapter is more detailed and has many texts (I am limited in Kung Fu, haha), but the idea should not be too complicated. There are only a few derivation chains, I hope that students who are new to this field will read it several more times and read it thoroughly. Then ...... Relax, drink tea, listen to music or something (I am tired too). Next time we will continue to talk about the principles and some applications of pointer declaration. Just like everyone else, I am only a beginner and enthusiast of C ++. Although I am ignorant, I like to think about some stray issues. If there are any mistakes, I hope all of my friends will point out, I am very grateful. If you have any suggestions or comments for this series, you are welcome to submit them. In short, we hope we can make common progress.

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.