The use of pointers in C ++

Source: Internet
Author: User
The use of pointers in C ++

Using pointers in C ++ programming has the advantages of high speed and memory saving. It is a favorite of many c ++ programmers. But a pointer is a double-edged sword. If you use it, you will find it very convenient. On the contrary, you may have a headache and unexpected problems.

1. What is a pointer:

In fact, pointers are like other variables. The difference is that common variables contain actual real data, while pointers are just an indicator, it tells the program where data can be found in the memory.

This is a very important concept. Many programs and algorithms are designed around pointers, such as linked lists and traversal.

A pointer is a data type that occupies four bytes of storage space. Therefore, the value obtained using sizeof (void *) is 4.

Ii. pointer Definition

See the following example:

Int * pnumber;

In this way, the int type pointer is defined.

The pointer variable name starts with P, which is a habit of programmers when defining pointers to improve the readability of the program. In addition, although int * pnumber and int * pnumber are the same, the latter programming style is better. For example:

Int * pnumber1, * pnumber2; indicates defining two pointers, with the number * approaching the variable. Otherwise, we may define it as int * pnumber1, pnumber2, which is an incorrect definition, pnumber2 is not a pointer.

Iii. Advantages of pointers

A. Provides the function with the means to modify and call the variable element;

B. Supports C ++ Dynamic Allocation subroutines

C. It can improve the efficiency of some subprograms.

D. Support for dynamic data structures (such as binary trees and linked lists)

Iv. pointer assignment and conversion:

A. directly assign values of the same type. convert values of different types.

B. Forced conversion: You can convert the expression result to a specified type.

C. char * p; (int *) p forcibly converts p to int type. Remember to pay attention to the size of the two types during the conversion process. data may be lost in an hour (such as int to double)

D. void:

In c, void * type can be assigned to any type of pointer, and vice versa

Mandatory conversion is required in c ++.

Void * can be regarded as infinite power to accept any type of value assignment. Otherwise, it cannot be int * p = 9; void * t = p (correct); p = t (incorrect)

E. Force conversion is required if void * is not involved.

5. pointers and Arrays

Returns the starting address of the array without the underlying array name, that is, the address of the first element of the array. There are two ways to access the array: array subscript and pointer arithmetic. For example:

Char * pChar;

Char chs [100];

PChar = chs; then pChar points to the first address of the chs array.

Vi. array and reference

A. the reference is only the alias of the variable, rather than the pointer to the variable (unlike the address-taking operator "&"), which does not occupy the memory space. Changes to the variable reference will also change the corresponding variable.

B. You cannot use the indirect pointer operator "*" for rereference.

C. The reference must initialize int & c = count; (c is the alias of count) during declaration)

7. Dynamic Allocation and recovery of pointer Space

Dynamic Allocation is a key technique of pointers. It is used to allocate memory and let pointers point to them without defining variables. Allocated memory. Do not forget to recycle it. You dynamically allocate a memory, but it will never be deleted automatically. That is to say, this memory space will always exist until you tell the computer that you have used up. The result is that you didn't tell the computer that you no longer need this memory space, so it will continue to occupy the memory space, resulting in waste, or even your program is running, it exists when other programs run. When such problems accumulate to a certain extent, the system will eventually crash. Therefore, it is very important to release the space after you use it.

8. Common Errors when using pointers

I have summarized the reasons for pointer errors as follows (in my personal experience, you are welcome to add ):

1. the pointer is not initialized.

Pointer Initialization is not a pointer definition, but an invalid value stored in the pointer variable. For example, define float a. This a will allocate an address, but the initial value is a mess of data. Similarly, float * a; will allocate an address for a, and the initial value is also messy data. During initialization, a = NULL can be added. In this way, if (a = NULL) can be added in future programs to determine whether the pointer is valid. Otherwise, the pointer will not work. Or allocate or specify space for the pointer. For example, float * a = new float; or float B; float * a = & B; can point the pointer to a piece of memory for initialization.

2. pointer out of bounds

Cross-border pointer is a hard-to-catch error. If the test is incomplete, it is not easy to detect. Programmers must always pay attention to the size of the space allocated to pointers.

3. pointer to a local variable

A pointer is a variable that records the starting address of a memory. To make the pointer valid, you must ensure that this memory is valid. The memory space allocated with New is always valid as long as it is not deleted. However, for pointers to a variable address, the programmer must understand the scope of the variable. If you leave the scope of the variable, the memory space of the variable will be automatically recycled by the system. When you use the pointer again, an error will occur. This is the most common error in the program.

4. pointer pointing to transfer

Some C ++ programmers often write such programs:

Char * pchar = new char;

Char CHS;

Pchar = & CHS;

Delete pchar;

They aim to pass the CHS content to the memory pointed to by the pchar pointer. However, this write will cause the spam address previously pointed to by pchar, because the address can no longer be obtained. It is commonly known as a wild pointer. This will cause memory leakage. In addition, an exception or error occurs when you call Delete pchar. Because the new space cannot be deleted using Delete. Because pchar has been directed to the address of the CHS variable.

The art of pointer is far more than that, and we will not wait for our fans to discuss it in depth. Pointers bring too much convenience to our programs. Similarly, they also have many difficult-to-control problems. How to better control the pointer can be said to be a means for C ++ programmers to improve themselves.

Article from: trackback: Postid = 1720477

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: 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.