Pointer and reference

Source: Internet
Author: User
Tags bitset

In September 24, I attended a research interview at South China University of Technology. During the interview, the teacher asked me about the difference between pointer and reference. Now I will explain in detail:

 

I. References

Simply put, a reference is the alias of a variable (alias). Through an alias, We can reference a variable. The syntax for defining a reference is as follows:

Variable type & reference identifier = variable name.

Exp:

int  iVar=10;  int  &iRef = iVar;  iRef = 20 ;  cout<<iVar<<endl;

 

The execution result of this program is output: 20;

The program changes the value of the variable Ivar by referencing iref.

Key points:

1. the colleague who defines the reference must initialize and point out which variable the reference represents, and this "pointing link" cannot be changed.

2. The reference is just another name of the object. You can access the object through the object's original identifier or through the object's reference.

3. When a statement defines multiple references, an & symbol must be added before each reference identifier (reference name). Otherwise, an error occurs.

 

1. const reference

A const reference is a reference to a const object. You cannot use a const reference to change the value of the original object. As follows:

 

1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <bitset> 5  6 using std::cin; 7 using std::cout; 8 using std::endl; 9 using std::string;10 using std::vector;11 using std::bitset;12 13 int main()14 {15     const int iVar=10;16     const int &iRef = iVar;17     iRef = 20; 18     cout<<iVar<<endl;19 20     return 0;21 }

 

 

The above program compilation result is as follows:

[[Email protected] cpp_src] # G ++ test. CPP test. CPP: In function 'int main () ': test. CPP: 17: Error: Assignment of read-only reference 'iref'

It can be found that in Row 3, an attempt is made to assign values to a const reference pointing to the const object, and an error is returned in the result compilation.

 1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <bitset> 5  6 using std::cin; 7 using std::cout; 8 using std::endl; 9 using std::string;10 using std::vector;11 using std::bitset;12 13 int main()14 {15     const int iVar=10;16     const int &iRef = iVar;17     iRef = 20;18 19     int &iRef1 = iVar;20     cout<<iVar<<endl;21 22     return 0;23 }

The program compilation result is as follows:

[[Email protected] cpp_src] # G ++ test. CPP test. CPP: In function 'int main () ': test. CPP: 17: Error: Assignment of read-only reference 'iref 'test. CPP: 19: error: the expression that initializes the reference of the type 'int & 'to the type 'const int' is invalid.

We found that when the program was compiled, row 19th also reported an error. The error type is: The expression of the reference initialization type const int of the type Int & is invalid.

2. Nominal value reference

You can define a const reference to represent the literal value. Example:

int main(){    int const &iRef = 100;    const string &strRef = "volcanol";    cout << iRef <<endl;    cout << strRef <<endl;    return 0;}

The execution result of the program is as follows:

[[email protected] cpp_src]# g++ test.cpp [[email protected] cpp_src]# ./a.out 100volcanol

Note: To define alias reference for a literal value, you must define the alias reference as a const type. Otherwise, a compilation error occurs.

 

2. pointer

What is a pointer? In some cases, a pointer is an address. We will not discuss the complex usage of pointers here. If you want to know the complex usage of pointers, you can refer to another article in the garden.

For: http://www.cnblogs.com/volcanol/archive/2011/06/05/2073042.html

1. pointer Definition

Defining a pointer in C ++ is very simple. when defining a variable, add a * Before the variable to define a pointer variable. Syntax:

The data type to be pointed to by the pointer * The Name Of The pointer variable;

Exp:

Int * pint; defines a pointer variable pint pointing to an integer variable;

String * pstr; defines a pointer to a string type object pstr;

Vector <int> * pvectorint; defines a pointer to the vector <int> container.

Bitset <5> * pbitset5; defines a pointer to an object of the bitset <5> type.

2. pointer variable assignment and initialization

Pointer variables must have a definite direction before they are used. Otherwise, a free pointer is generated, and the free pointer of the operation will produce an unexpected result. Obtain the address of a variable and assign it

The pointer variable or the initialization pointer variable gives the pointer variable a definite point. Get the address or (pointer) of a variable/object through the operator ).

Pointer variable initialization:

      int  iVar = 10;      int  *pInt = &iVar;

 

Pointer variable assignment:

      int iVar = 10;      int *pInt1;      int *pInt2;      pInt1 = &iVar;      pInt2 = pInt1;

 

3. Pointer Reference

The unreferencing operator * Can reference the variable pointed to by the pointer.

  int iVar = 20;  int *pInt = NULL;  pInt = &iVar;  cout<< * pInt<<endl;

Exp:

int main(){    int iVar = 100;    int *pInt = &iVar;    cout<<(*pInt)<<endl;    string strVar = "volcanol";    string *pStr = &strVar;    cout<<(*pStr)<<endl;    vector<int> vInt(1);    vector<int> *pVecInt=&vInt;    cout<<(*pVecInt)[0]<<endl;    bitset<5> bitVar(5);    bitset<5> *pBitset5 = &bitVar;    cout<< (*pBitset5) <<endl;    return 0;}

The execution result of the program is as follows:

[[email protected] cpp_src]# g++ test.cpp [[email protected] cpp_src]# ./a.out 100volcanol000101

Key points:

  When defining pointer variables, you must add * before each pointer variable. Otherwise, a non-pointer variable is defined.

Int * pint1, pint2; // pint1 is the pointer variable, and pint2 is the integer variable.

When defining pointer variables, there are two types of formats: int * pint and int * pint. There is no right or wrong between the two formats. Both formats are accepted, it may cause

Misunderstanding. In order to avoid misunderstanding, it is best to choose a format in a program to keep it.

 

 

4. pointer

A pointer variable is also an object. You can also define a pointer to it as a pointer. The syntax is as follows:

Pointer variable refers to the object type ** pointer variable identifier of the pointer;

Exp:

  int iVar = 10 ;  int *pInt = &iVar;  int **ppInt = &pInt;

The above defines a pointer variable ppint pointing to an integer pointer variable; ppint points to an object of the int * type.

int main(){    int iVar = 100;    int *pInt = &iVar;    int **ppInt = &pInt;    cout <<"iVar ="<< iVar<<endl;    cout <<"int *pInt = &iVar,then *pInt ="<<*pInt<<endl;    cout <<"int **ppInt = &pInt,then *ppInt="<<*ppInt;    cout <<";and then **ppInt="<<**ppInt<<endl;    return 0;}

The execution result of the program is as follows:

[[email protected] cpp_src]# g++ test.cpp [[email protected] cpp_src]# ./a.out iVar =100int *pInt = &iVar,then *pInt =100int **ppInt = &pInt,then *ppInt=0xbfb949f8;and then **ppInt=100

 

5. Access array elements through pointers

Here we need to describe the details: the array name of an array is a constant, and the array name represents the first address of the first element of the array, array elements are stored continuously in the memory.

It is precisely because the array has the above features that we can easily access the elements of the array through pointers.

An example of using a pointer to access an array element is as follows:

int main(){    int iArray[5] = {1,2,3,4,5};    int *pInt = iArray;    cout << *pInt << endl;  // 1    cout << pInt[0]<<endl;  // 1    cout << *++pInt<<endl;  // 2    cout << *pInt++<<endl;  // 2    cout << *pInt<<endl  ;  // 3    return
}

The execution result of the program is as follows:

[[email protected] cpp_src]# ./a.out 11223

Not only can the pointer point be changed through the ++ operator, but also supports integer addition and integer subtraction operations and subtraction operations on the two pointers.

int main(){    int iArray[5] = {1,2,3,4,5};    int *pInt1 = iArray;    int *pInt2= &iArray[4];    cout <<*(pInt1 + 2)<<endl;  // 3    cout <<*(pInt2 - 1)<<endl;  // 4    cout << pInt2 - pInt1 <<endl;    return 0;}

The execution result of the program is as follows:

[[email protected] cpp_src]# g++ test.cpp [[email protected] cpp_src]# ./a.out 344

Key points:

We can find that the pint2-pint1 result is 4, which is different from the C language output. Pay attention to this. In the process of combining pointers with arrays, the two pointers are subtracted.

Is a common operation, so pay attention to this place.

  

Through the above example, we can see that using pointers can easily access the elements of the array, so we can traverse the entire array through pointers.

int main(){    int iArray[5] = {1,2,3,4,5};    for(int *pBegin=iArray,*pEnd=iArray+5; pBegin != pEnd; ++pBegin)        cout<<*pBegin<<endl;    return 0;}

The execution result of the program is as follows:

[[email protected] cpp_src]# g++ test.cpp [[email protected] cpp_src]# ./a.out 12345

The definition between the pointer and the array also includes the * and [] symbols in the definition at the same time,

Exp:

 1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <bitset> 5  6 using std::cin; 7 using std::cout; 8 using std::endl; 9 using std::string;10 using std::vector;11 using std::bitset;12 13 int main()14 {15     int iArray_1[5] = {1,2,3,4,5};16     int iArray_2[3] = {1};17     int *pInt1[5] ={iArray_1, iArray_2};18     int (*pInt2)[5] = iArray_1; //error19     pInt2 = iArray_2;   //error 20 21 22     return 0;23 }

In the above code, I marked two errors because pint2 is a two-dimensional pointer, and iarray_1 and iarray_2 are both int * type pointers, if you modify the program, you can

The following result is displayed.

 1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <bitset> 5  6 using std::cin; 7 using std::cout; 8 using std::endl; 9 using std::string;10 using std::vector;11 using std::bitset;12 13 int main()14 {15     //int iArray_1[5] = {1,2,3,4,5};16     //int iArray_2[3]= {1};17     //int *pInt1[5] ={iArray_1, iArray_2};18     //int (*pInt2)[5] = iArray_1; //error19     //pInt2 = iArray_2;   //error 20 21     int iArray_1[5]={1,2,3,4,5};22     int iArray_2[3][5]={{1}};23     int iArray_3[5][3]={{2}};24     int (*pInt)[5] = iArray_2;25     pInt=iArray_3;  //error 26 27 28     return 0;29 }

In the code above, we can know that the 25 rows of syntax are incorrect because the two-dimensional array pointer length is inconsistent. Through the above example, we can know that * and [] define pointer variables together.

Note the priority of the * and [] symbols. The colleague needs to know the extension of the [] dimension after brackets are added. This is often used in C language and is a complicated usage, because

This requires special attention.

 

6. pointer and const qualifier/Modifier

The combination of the pointer and const does not have much to say about. The main reason is to pay attention to the * P or P Modified by const. It is easy to understand the differences between the modified objects as long as they are clearly divided.

int main(){    int iVar1 = 10;    int iVar2 = 20;    const int *pInt1 = &iVar1;    int const *pInt2 = &iVar1;    int * const pInt3 = &iVar1;    const int * const pInt4 = &iVar1;    int const * const pInt5 = &iVar2;    return 0;}

What you need to know about the const qualifier is the meaning of the above definitions. As long as you know whether const modifies * Pint or pint, You can accurately distinguish the meaning of each definition. For details, refer to the previous sections.

Links Related to interesting C language.

Here, we also need to note how the const object defines the pointer to it. The following is an example:

int main(){    const int iVar = 10;    //int *pInt1 = &iVar;  //error    int const *pInt1 = &iVar;    const int *pInt2 = &iVar;    return 0;}

Note the cause of some errors. This is not explained here. It has the same relationship with the const object and the reference.

 

7. Usage of pointers and typedef

In the C language, the process will execute such preprocessing commands.

#define  PINT  int*

In this way, the macro can be used to define pointer variables, as shown below:

#define PINT int*int iVar = 0;PINT pInt = &iVar;

This is acceptable, but there will be a vulnerability. If two pointer variables are defined at the same time, an error will occur.

#define  PINT int*int iVar1 = 0;int iVar2 = 0;PINT pInt1 = &iVar1,  pInt2 = &iVar2;

Obviously, the above Code has a vulnerability. The second variable pint2 is not a pointer variable, but an integer variable. Fortunately, the compiler will check this error during compilation, so it should be noted here.

We can use the typedef mechanism to avoid the above risks. The role of typedef is to take an alias for the data type, especially when the data type is relatively long, it is a very effective mechanism. The syntax of typedef

As follows:

Typedef data type alias;

For example:

  typedef  int*  PINT;

This defines a new alias pint for the int * type. When used, pint indicates int *.

Exp:

typedef  int*  PINT;int iVar1 = 0;int iVar2 = 0;PINT pInt1 = &iVar1,  pInt2 = &iVar2;

The code above defines two integer variables ivar1 and ivar2, and two pointer variables pint1 and pint2;

Key points:

Through the above two examples, we can understand the difference between typedef and # define.

Note that typedef is a statement, so it must end with a semicolon. This point is often easy to forget. Fortunately, the compiler can detect such errors.

  

The combination of typedef and pointer is also worth noting, that is, typedef, const, and pointer appear at the same time.

typedef  int* PINTconst PINT pInt;  //error

The pointer object pint defined here is the const pointer object, which must be initialized during definition. Therefore, pay attention to the above error.

 1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <bitset> 5  6 using std::cin; 7 using std::cout; 8 using std::endl; 9 using std::string;10 using std::vector;11 using std::bitset;12 13 int main()14 {15     typedef int* PINT;16     const PINT pInt;17 18     return 0;19 }

The program compilation result is as follows:

[[Email protected] cpp_src] # G ++ test. CPP test. CPP: In function 'int main () ': test. CPP: 16: Error: uninitialized constant 'pint'

It is correct to change the program to the following format:

# Include <iostream> # include <string> # include <vector> # include <bitset> Using STD: CIN; Using STD: cout; Using STD: Endl; using STD: string; Using STD: vector; Using STD: bitset; int main () {typedef int * pint; // const pint; int Ivar = 0; const pint = & Ivar; // initialize the const pointer return 0 ;}

Of course, you can also define more complex data types. We will not describe them here, but will describe them later.

 

Pointer operations are basically the same. In C ++, most people prefer not to use pointers, but pointers are indeed a very efficient mechanism, but if they can make good use of pointers, the

The performance improvement of the program has a very good improvement effect.

  

 

 

 

Pointer and reference

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.