A detailed introduction to the basic pointer of C ++ (1)

Source: Internet
Author: User

In IntroductionC ++InPointerBefore starting, we must first understand the concept and usage of arrays. You can refer to this article, "Analysis of Dynamic Multi-dimensional arrays in C ++" for your reference.

Array

In C ++, the memory is accessed through variables, but according to the previous instructions, C ++ can only use variables to operate the memory, that is, to operate a memory, you must first bind the first address of the memory to a variable name, which is terrible.

For example, if there are 100 pieces of memory to record the wages of 100 workers, we need to increase the wages of each worker by 5% now to know the wages of each worker after they increase, define a variable float a1; use it to record the wages of 1st workers, and then execute the statement a1 + = a1 * 0.05f;, then the increased salary is in a1. As there are 100 workers, There must be 100 variables, respectively recording 100 salaries. Therefore, the preceding value assignment statement requires 100 records, and each variable name is different.

You need to manually repeat the variable definition statement float a1; change the variable name 100 times each time), unnecessary work. Therefore, if you want to apply for 100*4 = 400 bytes of continuous memory from the operating system at one time, you need to change the salary for the worker I, you only need to add 4 * I bytes from the first address, because float occupies 4 bytes ).

To provide this function, C ++ proposes an array type. An array is a set of numbers. Each number is called an element of the corresponding array. The size of each element must be equal because the elements in the array are identified by a fixed offset ), that is, an array represents a group of numbers of the same type, which must be stored continuously in the memory. When defining a variable, to indicate that a variable is of the array type, add square brackets to the variable name, specify the number of array elements to be applied in square brackets, and end with a semicolon. Therefore, the above 100 wage variables can be defined as array variables as follows:

 
 
  1. float a[100]; 

The above defines a variable a, allocates 100*4 = 400 bytes of continuous memory because a float element occupies 4 bytes), and then binds its first address to variable name. The type of variable a is called an array with 100 float elements. The following will explain how the content type in the memory corresponding to variable a is the content in the memory): the memory ID of address a is the first address of a continuous memory, the size of this continuous memory can accommodate the next 100 float numbers.

Therefore, we can regard the previous float B as a float array variable B that defines an element. in order to access an element in the array, a number is placed in the square brackets after the variable name. The number must be a non-floating point number, that is, a number represented by a Binary source code or a complement code. For example, a [5 + 3] + = 32; that is, the value of the 5th + 3 element of array variable a is increased by 32:

 
 
  1. long c = 23;   
  2. float b = a[  c – 3 ) / 5 ] + 10, d = a[ c – 23 ]; 

The value of B above adds 10 to the value of the 4th elements of array variable a, and the value of d is the value of the 0th elements of array variable. That is to say, the elements in the C ++ array are numbered with 0 as the basic sequence number. That is, a [0] actually represents the value of the first element in array variable, 0 indicates that the address obtained after adding 0*4 to the address corresponding to a is the address of the first element.

Note that this cannot be written as follows:

 
 
  1. long a[0]; 

It is meaningless to define an array with 0 elements. The compiler will report an error, but this can be written after the structure or class or union meets certain rules, it is a technology proposed in the C language era to realize variable-length structure.

Note that variables cannot be written in square brackets when defining arrays, that is

 
 
  1. Long B = 10;
  2. Float a [B]; // It is incorrect

When compiling this code, you cannot know the value of variable B, and thus cannot allocate memory. But I already wrote B = 10. Why do I still know the value of B? That's because you cannot know the address corresponding to B.

Because the compiler only binds B to an offset during compilation, which is not the real address, that is, B may correspond to Base-54, the Base is the end address of the large block of memory dynamically applied to the operating system at the beginning of the program execution, because it may change, therefore, we cannot know that the actual address of B is in Windows. Because of the use of the virtual address space, the actual virtual address can be obtained, but it is still not the actual address, therefore, the value of a variable cannot be known during compilation ).

However, the compiler can still calculate the value of Base-54 as 10 based on the previous long B = 10? The point is that when the compiler sees long B = 10, it only knows to generate an instruction, which puts 10 into the memory of Base-54, and the rest will not ask or need to ask ), therefore, even if long B = 10 is written, the compiler cannot know the value of B.

Array is a type, which is not accurate. Actually, it should be -- array is a type modifier, which defines a type modifier. The Type modifier will be detailed later.

String

To check the ASCII code corresponding to A character, you must add single quotation marks on both sides of the character. For example, 'A' is equivalent to 65. to indicate multiple characters, use double quotation marks, for example, "ABC ". to record characters, you need to record the corresponding ASCII code, and the ASCII code value is within-128 to 127. Therefore, you can use a char variable to record an ASCII code, in order to record "ABC", it is normal to use an array of char to record. As follows:

No matter how many times the program executes, it always applies for a fixed size of memory when applying for memory, it is said that the memory is statically allocated. When we define variables, the memory allocated by the compiler from the stack is static. When you execute a program and may apply for memory of different sizes based on user input, the memory is dynamically allocated, and the allocation from the heap is dynamic.

Obviously, the dynamics are higher than static efficiency, and the invoice length utilization is higher), but the requirements are higher-computers and printers are needed, and cashiers are required to operate computers with higher quality ), static Requirements are relatively low. You only need the printed invoice, and only the cashier can write.

Similarly, the static allocated memory usage is not high or the usage is not flexible enough, but the code is easy to write and runs fast. The dynamic allocated memory usage is high, but it is more complicated to write code, you need to handle the management allocation and release of memory by yourself) and the operation speed is slow due to such management intervention and the code length increases.

Static and Dynamic are not only of this significance, but there are many improvements, such as hard coding and soft coding, tight coupling and loose coupling, which are both static and dynamic.

Address

As mentioned above, "an address is a number that uniquely identifies a specific memory unit", and then says, "The address is the same as a long integer or a single-precision floating point number, it is a type of number. "is the address both a number and a number? Isn't it a conflict?

The floating point number is a number-Decimal-and a number type. That is to say, the former is the actual use of the address, while the latter is because the computer only recognizes the status, but the type must be used to explain how to handle the status, the address type is used to tell the compiler to process the corresponding status with the memory unit identifier.

Pointer

We have learned that the dynamic and static memory allocation are different. Now we want to record the order data entered by the user. The number of orders entered by the user at a time is not fixed, so we choose to allocate memory on the stack. Assume that 1 MB of memory needs to be applied for temporary recording of user input data based on user input. In order to operate this 1 MB of continuous memory, the first address needs to be recorded, however, because the memory is dynamically allocated, that is, it is not allocated by the compiler but dynamically allocated by the program code), it is not possible to create a variable to map this first address, therefore, you must record the first address on your own.

Because any address is a 4-byte binary number pair of 32-bit operating system), a 4-byte memory is allocated statically to record this first address. Before checking, you can store the data at the first address in variable a of the unsigned long type, and then read the 4-byte long memory content at the 4th bytes in the memory of this 1 m, you can obtain the corresponding address by adding 4 to the value of a, and then retrieve the subsequent four bytes of memory. But how do I write code that retrieves the memory content corresponding to an address?

As mentioned above, as long as the number of the address type is returned, it will automatically retrieve the corresponding content because it is of the address type. But if you write a + 4 directly, because a is unsigned long, then a + 4 returns the unsigned long type, not the address type. What should we do?

C ++ puts forward an operator called "*", which is not accurate when the content operator is used ). It is the same as the multiplication operator, but it only connects numbers to the right, that is, * a + 4 ). This expression returns an unsigned long number after the value of a is 4 and converts it to an address-type number.

But there is a question: How does one explain the memory content expressed in a + 4? Is it one or two bytes? In what format is the extracted content interpreted? If you compile the assembly code yourself, this is not a problem, but now the compiler writes the assembly code on our behalf, therefore, you must tell the compiler how to explain the memory content of the given address.

C ++ puts forward a pointer to this. Like the above array, It is a type modifier. When defining variables, add "*" before the variable name to indicate that the corresponding variable is of the pointer type, just as "[]" after the variable name indicates that the corresponding variable is of the array type ), its size is fixed to 4 bytes. For example:

 
 
  1. unsigned long *pA; 

That is to say, when the type of an address is pointer, it indicates the content in the memory corresponding to this address, which should be interpreted as an address by the compiler.

Because the variable is the address ing, each variable has a corresponding address, so C ++ provides an operator to get the address of a variable -- "&", it is called the address fetch operator. It is the same as the "number and" operator, but it is always followed by a number on the right, not on both sides ).

The right side of "&" can only be an address-type number, and its calculation is Evaluate) it is to convert the numbers of the address type on the right to the pointer type and return a number of the pointer type, which is exactly the opposite of the "*" operator.

Under normal circumstances, the above should make you dizzy, and I will explain it below.

 
 
  1. unsigned long a = 10, b, *pA;   
  2. pA = &a;  
  3. b = *pA;   
  4.  *pA )++; 

The first sentence above defines a pointer type variable pA through "* pA", that is, the compiler helps us allocate a 4-byte memory on the stack, and bind the first address to the pA to form a ing ). Then "& a" is a variable, which is equivalent to an address, so "& a" is calculated and returns a number of the type: unsigned long *, that is, the pointer of unsigned long.

It should be noted that although the number returned above is a pointer type, its value is the same as the address corresponding to a, but why not directly say it is the number of the unsigned long address, what about the addition of a pointer type? Because pointer-type numbers directly return their binary values, address-type numbers return the memory content corresponding to their binary values. Therefore, if the address of the preceding variable a is 2000, a; returns 10, and & a; returns 2000.

Let's take a look at the content operator "*". The right-side numeric type is pointer type or array type, its calculation is to directly convert the number of this pointer type to the number of the address type, because the number of the pointer type is the same as the number of the address type, only the calculation rules are different ).

Therefore:

 
 
  1. b = *pA; 

Returns the address corresponding to pA, calculates the value of this address, returns the number 2000 of the unsigned long * type, and then "* pA" returns the number 2000 of the unsigned long Address type, then, calculate the value of the number of this address type, return 10, and then simply assign values. Similarly, for ++ * pA) because "*" has a lower priority than the prefix ++, ")" is added. calculate "* pA" and return the number 2000 of the unsigned long Address type, then calculate the prefix ++, and finally return the number 2000 of the unsigned long Address type.

If you still cannot understand the difference between the address type and the pointer type, we hope the following sentence can be useful: the number of the address type is used by the compiler during compilation, pointer-type numbers are used for code during runtime. If you still don't understand it, I hope it will be helpful after reading the type modifier section.

Subsequent articles>

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.