Use of pointers

Learning link:

http://www.icourse163.org/learn/ZJU-200001?tid=1002316004#/learn/content?type=detail&id=1003086473&cid=1003636045

Application scenarios of pointers

1. Swap two variables

2. Functions return multiple values, and some values ​​can only be returned through pointers

  The parameter passed in is actually the variable that needs to hold the result brought back

3. The function returns the state of the operation, and the result is returned by the pointer

What is the array passed into the function?

Arrays in function parameter tables are actually pointers

  sizeof(a)=sizeof(int *)

But you can use the array operator[] to operate

array parameter

The following four function prototypes are equivalent:

int sum (int * ar, int n

int  sum(int *,int)

int sum (int ar [], int n)

int sum(int [],int)

Array variables are special pointers

Array variables themselves express addresses, so

  int a[10]; int *p=a;

  However, the unit of the array expresses a variable, and you need to use & to take the address

  a==&a[0]

The [] operator can be done on arrays as well as on pointers:

  p[0]<==>a[0]

The * operator can be done on pointers as well as on arrays

  *a=25

Array variables are pointers to const, so they cannot be assigned

int a[] -->int * const a

pointer and const

The pointer is const, which means that once the address of a variable is obtained, it cannot be used to point to other variables.

  int * const q = &i ;

  * q =;26;

  q++;

Indicates that the variable cannot be modified through this pointer (and cannot make the variable const)

  const int * p= &i;

  *p = 26;error

  i = 26;ok

  p=&j ;ok

convert

1. It is always possible to convert a non-const value to const

2. When the type of the parameter to be passed is the currency address, this is a common method: it can not only pass a relatively small number of bytes to the parameter, but also avoid the modification of the external variables by the function

const array

const int a[]={1,2,3}

The array variable is already a const pointer, and the const here indicates that each element of the array is a const int

So it must be assigned by initialization

protect array value

Because the address is passed when the array is passed into the function, the value of the array can be modified inside the function

In order to protect the array from being destroyed by the function, you can set the parameter to const

  int sum (const int a[], int length);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324988818&siteId=291194637