(reprint) Hello, C + + (15) four-and-a---3.9 pointer to memory location

Source: Internet
Author: User

3.9 Pointer to memory location

One day, two variables were encountered on the street:

"Where do you live, man?" I'll see you sometime. ”

"Oh, my home in the static storage area of the 0x0049a024 number, where's your home?" ”

"My home in the dynamic storage area of the 0x0022ff0c number. Have time to play. ”

In the previous chapters, we learned to use numeric data types such as int to express various numeric data, to express literal data with char data types, and we can even use structs to combine multiple basic data types to form new data types to express more complex things. In addition to these common data in the real world, in program design, we have another kind of data that we often need to deal with, which is the variable or function in memory address data. For example, 0x0049a024 and 0x0022ff0c in the conversation above are two variables in memory address. As the conversation says, we can easily read and write access to the variable's address in memory, so memory address data is often used in programs. In C + +, variables that represent memory address data are referred to as pointer variables, or pointers, for short.

pointers, which C + + inherits from the C language, provide a simple, efficient way to access memory directly. In particular, when the amount of data to be accessed is relatively large, such as a large volume of structural variables, directly through the pointer to the memory of the variable, rather than moving the copy variable to access it much faster, can play 42 of the weight of the effect. By using pointers correctly, you can write more compact, efficient code. However, if the use of pointers is not appropriate, it is easy to produce serious errors, and these errors are also a certain concealment, extremely difficult to find and fix, so it has become the source of the pain of millions of programmers. Love and hate intertwined, is the programmer to the pointer of the greatest feeling, and learn pointers, with good pointers, also become a required for each C + + programmer.

3.9.1 the Access form of the memory space

Pointers are specifically used to represent memory addresses, and their use is closely related to memory access. To better understand pointers, let's look at the form of access to memory space in C + +.

In a C + + program, there are two ways to access memory. One is accessed indirectly through the variable name. In order to save the data, the variables that hold the data are usually defined first. Defining variables also means that the system allocates a certain amount of memory space to store some data, and the variable name becomes the identity of the memory area. With variable names, we can indirectly access the area of memory where the data is read or written.

Another way is to access the data on the address directly through the memory where the data resides, that is, through pointers.

Both of these are methods of accessing memory in C + +, just a direct one indirectly. Make an inappropriate metaphor, for example, to send a parcel (data) to somewhere (an area in memory). In the first way, we said: Send to the Asian American Building (variable name). And in the second way, we will say: Send To Technology road 83rd (memory address). Although the two forms of expression are different, the same thing is actually said.

On a typical 32-bit computer platform, memory space can be thought of as a number of contiguous small rooms, each room is a small storage unit, the size is a byte (byte), and the data live in these rooms. Some of the data is small, such as a char type character, it only needs a room to be enough. And some of the data is relatively large, you need to occupy several rooms. An integer of type int, for example, is 4 bytes in size and requires 4 rooms to be placed. In order to conveniently find the data that lives in these rooms, the room is numbered according to a certain rule, and this number is the usual memory address. These numbers are usually represented by a 32-digit hexadecimal number, such as 0x0049a024, 0x0022ff0c, and so on in the example above, as shown in 3-6.

Figure 3-6 the data that lives in memory

Once you know the room number in which a data is located, you can read and write access to the data in the corresponding room directly through this number. As in the example above, we can also save the data directly to 0x0022ff0c, just as the parcel is delivered directly to technology Road No. 83rd.

3.9.2 the definition of a pointer variable

Pointers, as a special variable representing memory addresses, have certain peculiarities in the form of definitions:

Data type * variable name;

In this case, we use the data type on the address represented by the pointer as the data type used to define the pointer variable. For example, if we want to define a pointer to represent the address of an int type of data, then the data type in the pointer definition is int. This data type is determined by the data that the pointer points to, such as the base data type int, string, and double, or a complex data type such as a custom struct body. In short, what type of data the pointer points to is the type of data that is defined with this type as a pointer variable. The "*" symbol after the data type indicates that a pointer variable is defined. The "variable name" is the name given to the pointer. For example:

defines the pointer variable p, which can record the address of an int type of data int* p;  defines the pointer variable pemp, which can record the address of an employee type data employee* pemp    

Best practice: Choosing the right way to define pointer variables

In fact, the following two definitions of pointer variables are in the form of C + + syntax:

int* p;  int *p; 

Both of these forms can be compiled through and represent the same syntactic meaning. However, the programming styles reflected in these two forms are different from those emphasized by code readers.

"Int* P" emphasizes that "p is a pointer to an int type integer", where int* can be seen as a special data type, while the entire statement emphasizes that p is a variable of this data type (int*).

"Int *p" is the *p as a whole, emphasizing that "this pointer is pointing to an integer of type int", and p is a pointer to this integer.

There is no difference between the two forms of right and wrong, only the difference between personal preferences. This book recommends the first form, which treats pointers as a data type, and defines pointers to variable statements that are clearer and more readable.

In particular, when you define multiple pointer variables in a single statement, it can be confusing, for example:

p is a pointer variable of type int, and q is actually a variable of type int // may make people mistakenly think P and q are int type pointer int* p, q;  clear: *p is an integer, p is a pointer to this integer, q is also an integer int *p, q;  defines two pointers to the int type data p and qint *p, *q;           

In development practice, there is a code specification: "One statement only accomplishes a thing". According to this specification, if we define p and Q separately, we can avoid these problems well.

If we do need to define multiple pointer variables of the same type, we can also use the TypeDef keyword to define the pointer type as a new data type, and then define multiple pointer variables with this new data type:

defines the Employee pointer type as a new data type empointertypedef employee* empointer;  define multiple pointer variables with the Empointer type, which are "employee*" types Empointer pcao,pcbo,pcco,pcdo;   

Assignment and use of 3.9.3 pointers

After you have defined a pointer variable, the value of the pointer variable is still a random value. It may be pointing to an insignificant data, but it may also be important data or program code, if the consequences of direct use are not predictable. Perhaps nothing, perhaps caused the destruction of the Earth. So before you use the pointer, you must initialize it with a value that points to a meaningful, legitimate memory location. The syntax format for assigning pointer variables is as follows:

Pointer variable = memory address;

As you can see, the assignment of a pointer variable is actually pointing to a memory address where the data that the pointer wants to point is stored. We know that the data is represented by a variable, and the memory address of the variable is equal to the memory address where the data is located, and then it can be used to assign a value to the pointer variable. In C + +, we can take the "&" address operator, put it in front of a variable, you can get the memory address of the variable. For example:

define an integer variable to represent the integer data 10031003;  define integer pointer variable pn, use "&" symbol to get address of integer variable N,// and assign it to integer pointer variable pnint* pn = &N;       

Here, we use the "&" notation to get the memory address of the integer variable n, which is the memory address where the integer data is 1003, and then assigns it to the integer pointer variable pn, which points to 1003 of the data in the pointer pn. As shown in 3-7.

Figure 3-7 The data pointed to by the pointer and pointer

The initialization assignment of pointers is best done at the same time as the pointer is defined, as in the example above, when the pointer pn is defined, the memory address of the variable n is assigned to it, so that the pointer has a reasonable initial value at the beginning, preventing the uninitialized pointer from being used incorrectly. If you do not have a reasonable initial value when defining a pointer, we can assign it to the NULLPTR keyword, which indicates that the pointer does not point to any memory address, is a null pointer (null pointer), and is not available. For example:

define a pointer variable pn, which is assigned to nullptr to indicate that it does not point to any memory location // Here just defines the variable, and then uses int* PN = nullptr;  ..... // determine if PN points to a certain data // If the value of PN is not a nullptr initial value, it means that it is re-assigned to a data if (nullptr! =/ / Use the PN pointer to access the data it points to}             

You can use "&" to obtain the memory address of a data, in turn, we can also use "*" to obtain a memory address on the data. "*" is called the pointer operator, also known as the parse operator. It performs the exact opposite of the "&" operator. If you put it in front of a pointer variable, you can get the data on the memory address that the pointer points to. For example:

output PN points to the memory address 0x0016fa38cout<<pn<<Endl;  The "*" Sign gets the data "1003" on the memory address pointed to by the PN and outputs // equals to the cout<<n<<endl;cout<<*pn<<Endl;  Modify the data//1982 it points to by the pointer ;  Output the modified data "1982" cout<<*pn<<endl;             

The "*" operator can obtain the data variable n which the PN pointer points to, although "N" and "*PN" are different in form, but they all represent the same data in memory, both can read/write the data, and is equivalent.

In particular, if a pointer is pointing to a variable of a struct type, use "." With struct variables. The symbol derivation member variable is different, if is a pointer to the struct body, then should use "with" the symbol to draw its member variable. This symbol, much like a pointer. For example:

define a struct variable Employee  Zengmei;  define a pointer and point it to the struct variable employee* pzengmei = &Zengmei;  "Zengmei";         

Best practice: Try to avoid pointing two pointers to the same variable

When a pointer variable is correctly assigned to a variable, it becomes a valid memory address, or it can be used to assign a value to another pointer. This way, two pointers have the same memory address, pointing to the same content. For example:

define an Integer variable 1982;  get the memory address of variable A and assign a value to the pointer paint* PA = &A;  use PA to another pointer pb assignment int* PB = pa;         

Here, we assign the pointer PB with a pointer to the variable A, so that the values of PA and PB are the same, which is the address of variable A, that is, two pointers point to the same variable.

It is worth noting that although the two pointers to the same variable are syntactically legal, they should be avoided in actual development. With a little attention, this code can be confusing. Continue with the above example:

output PA points to the data, for 1982cout<<*pa<<Endl;  1003;  output PA-directed data again, and become 1003cout<<*pa<<endl;      

If we just look at the output of this program, it will be strange: why not make any changes through PA, and the content of the two output is different? If we combine the previous code, we will understand that PA and Pb point to the same variable a, when we modify the variable a by the pointer Pb, and then through the PA to obtain the data of variable A, is naturally updated. On the surface, the variable A is not modified by PA, and PB is already sneak, and the data of variable A is changed secretly. In the program, this sneaky behavior is the most taboo, because once this behavior causes the program to run wrong, it will be difficult to find. Therefore, try to avoid two pointers pointing to the same variable, just as it is best not to take two names as a person.

Original address: http://www.cnblogs.com/nihaoCPP/p/4042897.html

(reprint) Hello, C + + (15) four-and-a---3.9 pointer to memory location

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.