Features of pointers

Source: Internet
Author: User

This is the best entry-level article on pointers I have ever seen. It allows beginners to learn complex pointer operations in a short time. Although pointers have been removed from Java, C #, and other languages, as a C ++ programmer, direct pointer operations on memory are fast in terms of data operations, memory saving and other advantages are still the favorite of many c ++ programmers. The pointer is like a good sword. It depends on how you apply it!

What is a pointer?

In fact, pointers are like other variables. what is different is that common variables contain actual real data, while pointers are indicators, 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.

Start learning

How to define a pointer? Just like defining another variable, you need to add an asterisk before the pointer name. Let's look at an example:
The following program defines two pointers, both pointing to integer data.

Int * pnumberone;
Int * pnumbertwo;

Have you noticed the "P" prefix before the two variable names? This is a common habit of programmers when defining pointers to improve the readability of convenience programs, indicating that this is a pointer. Now let's initialize these two pointers:
Pnumberone = & some_number;
Pnumbertwo = & some_other_number;
"What address" is returned as the address of the variable in the memory instead of the value of the variable itself. In this example, pnumberone is equal to the some_number address, so now pnumberone points to some_number. If some_number is used in the program, we can use pnumberone.

Let's take an example:

In this example, you will learn a lot. If you do not know the pointer concept at all, I suggest you read the example several times. Pointers are very complicated, 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 the code written in C, and the translator rewrite all the code with C ++ again, and compiled in Dev C ++ and VC ++ !)

# Include <iostream. h>

Void main ()
{
// Declare the variable:
Int nNumber;
Int * ppointer;

// Assign values to them now:
NNumber = 15;
Ppointer = & nNumber;

// Print the nNumber value of the variable:
Cout <"nNumber is equal to:" <nNumber <Endl;

// Now use the pointer to change the value of nNumber:
* Ppointer = 25;

// Prove that nNumber has been changed by the above program
// Print the nNumber value again:
Cout <"nNumber is equal to:" <nNumber <Endl;
}

Read this program, compile and run it, and understand how it works. If you have finished, prepare and start the next section.

Trap!

Can you find out the following program errors?

# Include <iostream. h>

Int * ppointer;

Void somefunction ();
{
Int nNumber;
NNumber = 25;

// Point the pointer to nNumber:
Ppointer = & nNumber;
}

Void main ()
{
Somefunction (); // assign a value to ppointer

// Why does this fail? Why not get 25
Cout <"value of * ppointer:" <* ppointer <Endl;
}

This program first calls the somefunction function, creates a variable named nNumber, and then points the pointer ppointer to it. But where is the problem? When the function ends, the nNumber is deleted because of this local variable. After the execution of the function that defines a local variable, it is automatically deleted by the system. That is to say, when the somefunction returns the main function main (), this variable has been deleted, but ppointer also points to the area where the variable has been used but is no longer in this program. If you still don't understand it, you can read this program and pay attention to its local variables and global variables. These concepts are very important.
But how can this problem be solved? The answer is dynamic allocation technology. Note that this is different in C and C ++. Most programmers use C ++, so I use the frequently-used title in C ++.

Dynamic Allocation

Dynamic Allocation is a key technique of pointers. It is used to allocate memory and let pointers point to them without defining variables. Although this may confuse you, it is actually very simple. The following code allocates memory for an integer data:
Int * pnumber;
Pnumber = new int;
The first row declares a pointer pnumber. The second action is to allocate a memory space for an integer and point pnumber to the new memory space. The following is a new example. This time, the doubledual-precision model is used:
Double * pdouble;
Pdouble = new double;
This format is a rule, so you will not be wrong.
But what is the difference between dynamic allocation and the previous example? The memory area you allocated will not be deleted when the function is returned or executed. Therefore, we can use dynamic allocation to rewrite the above program:
# Include <iostream. h>

Int * ppointer;

Void somefunction ()
{
// Point the pointer to a new integer
Ppointer = new int;
* Ppointer = 25;
}

Void main ()
{
Somefunction (); // assign a value to ppointer

Cout <"value of * ppointer:" <* ppointer <Endl;
}
Read this program, compile and run it, and understand how it works. When somefunction is called, it allocates a memory and points ppointer to it. This time, when the function returns, the new memory area is retained, so ppointer always points to useful information because of dynamic allocation. But if you read the above program carefully, although it has obtained the correct results, there is still a serious error.

Memory allocated. Don't forget to recycle it.

It's too complicated. How can there be serious errors! In fact, it is not difficult to make corrections. The problem is: 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, for example:
Delete ppointer;
You have to be careful. Here you terminate a valid pointer (a pointer that actually points to a memory ).
The following program will not waste any memory:

# Include <iostream. h>

Int * ppointer;

Void somefunction ()
{
// Point the pointer to a new integer
Ppointer = new int;
* Ppointer = 25;
}

Void main ()
{
Somefunction (); // assign a value to ppointer
Cout <"value of * ppointer:" <* ppointer <Endl;

Delete ppointer;
}

Only one line is different from the previous program, but the last line is very important. If you do not delete it, you will create a "memory Vulnerability" to gradually leak the memory.
(TRANSLATOR: If I call somefunction twice in a program, how do you modify this program? Please think for yourself)

Pass pointer to function

It is very useful and easy to pass pointers to functions. If we write a program and add a number to 5, will the program be 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;
// Do you get result 23? Where is the problem?
}
The problem is that the number used in the addfive function is a copy of the variable nmynumber and passed to the function, not the variable itself. Therefore, the "number = Number + 5" line adds 5 copies of the variable, while the original variable remains unchanged in the main () function. Try to run this program and try it yourself.
To solve this problem, we need to pass a pointer to the function, so we need to modify the function so that it can accept the pointer: Put 'void addfive (INT number) 'Change to 'void addfive (int * Number )'. The following is the modified program. When calling a function, use the & sign 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 by yourself. Note the importance of adding the * sign before the parameter number of the addfive function: it tells the compiler that we add 5 to the variable referred to by the pointer. Instead of adding 5 to the pointer.

Finally, if you want the function to return a pointer, you can write it like this:
Int * myfunction ();
In this sentence, myfunction returns a pointer to an integer.

Pointer to class

Exercise extra caution when using pointers in a class. You can use the following method to define a class:
Class myclass
{
Public:
Int m_number;
Char m_character;
};
Then you can define a variable of the myclass class:
Myclass thing;
You already know how to define a pointer:
Myclass * thing;
Then you can allocate a memory space for it:
Thing = new myclass;
Note that the problem occurs. How are you going to use this pointer? Generally, you may write 'thing. m_number ', but is thing a class? No, it is a pointer to a class, and it does not contain a variable named m_number. So we must use another method: replace '.' (point number) with->. Let's look at the example below:
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 perform the following operations:
Int * parray;
Parray = new int [6];
The program will create a pointer parray to point it to an array with six elements. Another method is not to dynamically allocate:
Int * parray;
Int myarray [6];
Parray = & myarray [0];
Note: & myarray [0] can also be abbreviated as myarray, indicating the address of the first element of the array. However, if parray = & myarray is written, a problem may occur. The result is that parray points to the pointer to the array (although it is equal to & myarray [0] In a one-dimensional array ), instead of what you want, it is easy to make errors in multi-dimensional arrays.

Use Pointer in array

Once you define a pointer to an array, how do you use it? Let's look at an example of a pointer to an integer array:

# 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 want the pointer to point to the next element in the array, you can use parray ++. You can also use parray + 1 that you can think of to point the pointer to the next element of the array. Note that when you move the pointer, the program does not check whether you have moved beyond your defined array, that is to say, you are likely to access data outside the array through the simple pointer and operation above, and the result is that the system may crash, so please be very careful.
Of course, with parray + 1, you can also have parray-1. This operation is often used in loops, especially in the while loop.
Another thing to note is that if you define a pointer to an integer: int * pnumberset, you can think of it as an array, for example: pnumberset [0] And * pnumberset are equal, and pnumberset [1] and * (pnumberset + 1) are equal.
At the end of this section, a warning is given: If you use new to dynamically allocate an array,
Int * parray;
Parray = new int [6];
Don't forget to recycle,
Delete [] parray;
This statement tells the compiler to delete the entire array instead of a single element. Remember.

Remarks

Also, be careful not to delete a pointer that does not allocate memory at all. Typically, delete is not used if the new allocation is not used:

Void main ()
{
Int number;
Int * pnumber = number;

Delete pnumber; // error-* pnumber does not use new to dynamically allocate memory.
}

FAQs

Q: Why do I always encounter the 'symbol undefined' error in the new and delete statements during program compilation?
A: both new and delete are c ++ extensions on C. This error indicates that the compiler considers your current program as C rather than C ++, and of course it will make an error. Check whether your file name ends with. cpp.

Q: What is the difference between new and malloc?
A: New is a standard function used to allocate memory in C ++. Do not use malloc in C ++ unless necessary. Because malloc is a syntax in C, it is not designed for Object-Oriented C ++.

Q: Can I use free and delete at the same time?
A: You should note that the operations they match are different. Free is only used for memory operations allocated with malloc, while Delete is only used for memory operations allocated with new.

Reference (to some competent readers)

This section is not the center of my article, but for some competent readers.
Some readers often ask me questions about references and pointers. Here I will briefly discuss them.
In the previous pointer learning, we know that (&) is the address for reading "what", but in the following program, it is a reference for reading "what"

Int & number = myothernumber;
Number = 25;
The reference is a pointer to the myothernumber. The difference is that it is automatically deleted. So it is more useful than pointers in some scenarios. The equivalent code above is:
Int * pnumber = & myothernumber;
* Pnumber = 25;
Another difference between a pointer and a reference is that you cannot modify the reference you have defined, that is, you cannot change the content it refers to during the declaration. For example:
Int myfirstnumber = 25;
Int mysecondnumber = 20;
Int & myreference = myfirstnumber;

Myreference = mysecondnumber; // can this step change myreference?

Cout <myfristnumber <Endl; // is the result 20 or 25?

When operating in a class, the referenced value must be set in the constructor. For example:

Cmyclass: cmyclass (Int & variable): m_myreferenceincmyclass (variable)
{
// Constructor code here
}

Summary

This article may be difficult to grasp at the beginning, so it is best to read it several times more. Some readers cannot understand it yet. Here I will make a brief summary:
A pointer is a variable pointing to the memory area. It is defined with an asterisk (*) before the variable name (for example, int * number ).
You can get the address of any variable and add & (for example, pnumber = & my_number) before the variable name ).
You can use the 'new' keyword to dynamically allocate memory. The pointer type 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 the function. You must use 'delete' to delete your dynamically allocated memory.
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.

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.