当前位置:网站首页>Hello C (III) - pointer

Hello C (III) - pointer

2022-06-24 23:41:00 Tianshan old demon

Pointer is C A data type widely used in languages , yes C The soul of language . Pointers provide a mechanism for dynamically manipulating memory , Enhanced support for data structures , And it realizes the function of accessing hardware . Learning pointer is learning C The most important part of language , Whether we can correctly understand and use the pointer is whether we master C A sign of language .

One 、 The concept of pointer

In the computer , All data is stored in memory , Generally, a byte in memory is called a memory unit , Different data types occupy different memory units , Such as int Occupy 4 Bytes ,char Occupy 1 Bytes . In order to access memory cells correctly , Each memory unit must be numbered . The number of each memory unit is unique , The memory unit can be found accurately according to the number . The number of the memory unit is called the address (Address), Also called a pointer (Pointer). So the key to understanding pointers is to understand C How programs manage memory .

Pointer of memory unit and content of memory unit are two different concepts . We can use a popular example to illustrate the relationship between them . Each of us has a unique ID card account , The ID card stores the identity information of each of us , The ID number is the pointer to the account , Identity information is the content of the account . For a memory unit , Address of the unit ( Number ) Is the pointer , The data stored in it is the content of the unit .
stay C In language , The variables that store pointers are called pointer variables . The value of a pointer variable is the address of a memory unit or the pointer to a memory unit .

Pointers are essentially variables that store addresses .
Set character variables c, Its content is 'K'(ASCII The code is decimal 75),c Occupied 0X11A Memory unit no ( Addresses are usually represented by hexadecimal numbers ). Set pointer variable p, The content is 0X11A, This is what we call p Point to variable c, Or say p Is pointing to variables c The pointer to .

Two 、C Language pointer type analysis

1、C Analysis of common pointer types in language

int p;

p Is a common integer variable

int *P;

First of all, from the P Start at , With the first * combination , So explain P It's a pointer , And then with int combination , Indicates that the type of content the pointer points to is int type . therefore P Is a pointer to return integer data

int P[3];

First of all, from the P Start at , With the first [] combination , explain P Is an array , Then with int combination , Indicates that the elements in the array are integer , therefore P Is an array of integer data  

int *P[3];

First of all, from the P Start at , With the first [] combination , Because of its priority ratio * high , therefore P Is an array , And then with * combination , Indicates that the elements in the array are pointer types , And then with int combination , Indicates that the type of the content pointed to by the pointer is integer , So it's an array of pointers that return integer data  

int (*P)[3];

First of all, from the P Start at , With the first * combination , explain P Is a pointer and then with [] combination ( And "()" This step can be ignored , Just to change priorities ), The content pointed to by the pointer is an array , And then with int combination , Indicates that the elements in the array are integer . therefore P Is a pointer to an array of integer data  

int **P;

First of all, from the P Start , With the first * combination , explain P It's a pointer , And then with * combination , Indicates that the element pointed to by the pointer is a pointer , And then with int combination , Indicates that the element pointed to by the pointer is integer data . therefore P Is a pointer that returns a pointer to integer data  

int P(int); 

from P From the beginning , With the first () combination , explain P It's a function , Then enter () Li analysis , It indicates that the function has an integer variable parameter, and then it is connected with the external int combination , The return value of the function is an integer data . therefore P Is a function with integer parameters and an integer return type  

int (*P)(int);

from P Start at , Combine with pointer first , explain P It's a pointer , Then with () combination , The pointer points to a function , And then with () Inside int combination , It shows that the function has a int The parameters of type , And then with the outermost int combination , The return type of the function is integer , therefore P Is a pointer to a function with an integer parameter and an integer return type  

int *(*P(int))[3];

from P Start , With the first () combination , explain P It's a function , Then enter () Inside , And int combination , The function has an integer variable parameter , Then with the outside * combination , The function returns a pointer ,, Then go to the outermost floor , With the first [] combination , Indicates that the returned pointer points to an array , And then with * combination , Indicates that the elements in the array are pointers , And then with int combination , Indicates that the content pointed to by the pointer is integer data . therefore P Is a function whose parameter is an integer and returns a pointer variable pointing to an array of integer pointer variables .

2、 Pointer analysis

A pointer is a special variable , The value stored in it is interpreted as an address in memory .  To understand a pointer, we need to understand four aspects of the pointer : The type of pointer 、 The type that the pointer points to 、 The value of the pointer or the memory area the pointer points to 、 The memory area occupied by the pointer itself .
A、 The type of pointer

Remove the pointer name from the pointer declaration statement , The rest is the type of the pointer  
B、 The type that the pointer points to

The pointer name in the pointer declaration statement and the pointer declarator to the left of the name * Get rid of , The rest is the type the pointer points to ( In pointer arithmetic operations , The type that the pointer points to has a big effect ) 
C、 The memory area pointed to by the pointer

The pointer variable must be assigned after it is defined before it can be used , The memory area pointed to by the pointer starts from the memory address represented by the value of the pointer , The length is sizeof( The type that the pointer points to ) A piece of memory . A variable pointer points to a memory area , It is equivalent to saying that the value of the pointer variable is the first address of this memory area . If the memory area pointed to by the pointer variable is not initialized , Then the memory area stores garbage data . Just like if a variable is not assigned a value after it is defined, it will be a garbage value , After the pointer is defined, it must also assign a value to specify the legal memory address , Otherwise, dereference will cause errors ( Segment error )
 D、 The memory area occupied by the pointer itself

Use functions sizeof( The type of pointer ) The memory area occupied by the pointer itself can be measured ( stay 32 In the platform , The pointer itself occupies 4 The length of bytes ) .

3、 Cast pointer

When we initialize a pointer or assign a value to a pointer , To the left of the assignment number is a pointer , To the right of the assignment number is a pointer expression , This requires the same type on both sides , The same type is pointed to , If not , You need to cast . The syntax is :(TYPE *)p.

So the result of the cast is a new pointer , The type of the new pointer is TYPE *, The type it points to is TYPE, The address it points to is the address pointed to by the original pointer . It should be noted that , The original pointer p None of the properties of have been modified . 

in addition , If a function uses a pointer as a formal parameter , Then in the combination of arguments and formal parameters of function call statements , You must also ensure that the types are consistent , Otherwise forced conversion is required .

4、const With the pointer

const int *p; The pointer p As a variable , The memory space pointed to by the pointer stores constants

int const *p; The pointer p As a variable , The memory space pointed to by the pointer stores constants

int * cosnt p; The pointer is a constant , The memory space pointed to by the pointer stores variables

const int * const p; The pointer is a constant , The memory space pointed to by the pointer stores constants

5、 Wild pointer

A wild pointer is a pointer to an address that is unpredictable . Wild pointers are easy to trigger runtime errors . Generally speaking , After the pointer is defined, if it is used without assignment, it is a wild pointer , The memory address space pointed to is indeterminate . The general practice of avoiding wild pointers :

A、 Initializes to... When defining a pointer NULL

B、 Assign a value to the pointer before dereferencing it

C、 Check whether the pointer is before dereferencing the pointer NULL

D、 Assign a value after the pointer is used NULL

int a;
int *p = NULL;
p = &a;
if(NULL != p)
{
    *p = 3;
}
p = NULL;

3、 ... and 、 Assignment of pointer variables

Pointer variables are the same as ordinary variables , Before you use it, you should not only define the description , And it has to be given a specific value . An unassigned pointer variable cannot be used , Otherwise, it will cause system chaos , Even crashes . A pointer variable can only be assigned an address , Never give any other data , Otherwise, it will cause mistakes . stay C In language , The address of the variable is assigned by the compilation system , Completely transparent to users , The user does not know the specific address of the variable . C Address operators are provided in the language & To represent the address of a variable . Its general form is : & Variable name ; Such as &a Variable indication a The address of ,&b Said variable b The address of . The variable itself must be specified in advance . There are two ways to assign pointer variables :

1、 Pointer variable initialization method

int a;
int *p = &a;


2、 Method of assignment statement

int a;
int *p;
p = &a;


It is not allowed to assign a number to a pointer variable , So the following assignment is wrong : int *p;p=1000; The assigned pointer variable cannot be preceded by “*” specifier , If it is written as *p=&a It's also wrong

Four 、 Operation of pointer variable

Pointer variables can perform certain operations , But the kinds of operations are limited . It can only carry out assignment operation, partial arithmetic operation and relation operation .

1、 Pointer operator

A、 Fetch address operator &
Fetch address operator & It's a monocular operator , Its binding ability is from right to left , Its function is to get the address of the variable .&a The result of the operation is a pointer , The type of pointer is a Add a type of *, The type the pointer points to is a The type of , The address the pointer points to , That's it a The address of .

B、 Take the content operator *
Take the content operator * It's a monocular operator , Its binding ability is from right to left , Used to represent the variable that a pointer variable refers to . stay * The variable following the operator must be a pointer variable . Note that the pointer operator * And pointer specifiers in pointer variable descriptions * It's not the same thing . In the pointer variable description ,“*” It's a type specifier , Indicates that the following variable is a pointer type . And in the expression “*” Is an operator , Used to represent the variable that the pointer variable refers to .

2、 Operation of pointer variable

A、 The assignment operation

There are several forms of pointer variable assignment :

Pointer variable initialization assignment

Assign the address of a variable to a pointer variable pointing to the same data type

int a,*pa;

pa=&a; /* Put the integer variable a The address of is assigned to an integer pointer variable pa*/

Assign the value of a pointer variable to another pointer variable pointing to a variable of the same type

int a,*pa=&a,*pb;

pb=pa; /* hold a The address of the given pointer variable pb*/

Assign the first address of an array to a pointer to the array

int a[5],*pa;

pa=a; ( The array name indicates the first address of the array , So you can give a pointer variable to an array pa)

Assign the first address of a string to a pointer variable pointing to a character type .

char *pc;pc="c language";

char *pc="C Language";

Give the function's entry address to the pointer variable to the function

int (*pf)();

pf=f; /*f For function name */

B、 Addition and subtraction

Pointer variable plus or minus an integer n It means to point the pointer to the current position ( Point to an array element ) Move forward or backward n A place . It should be noted , An array pointer variable moves forward or backward one position and address plus 1 Or minus 1 It's conceptually different . Because arrays can have different types , The byte length of each type of array element is different . Such as pointer variable plus 1, It's moving backwards 1 A position indicates that the pointer variable points to the first address of the next data element . Instead of adding... To the original address 1.

int a[5],*pa;
pa=a; /*pa Pointing to the array a, It's also a direction a[0]*/
pa=pa+2; /*pa Point to a[2], namely pa The value of is &pa[2]*/ The addition and subtraction of pointer variables can only be performed on array pointer variables , It is meaningless to add and subtract pointer variables pointing to other types of variables .

C、 Operations between pointer variables

The operation between two pointer variables can only be performed between two pointer variables pointing to the same array , Otherwise, the operation is meaningless .

Subtracting two pointer variables

The difference obtained by subtracting two pointer variables is the number of elements of the difference between the two pointer groups . It's actually two pointer values ( Address ) The difference is then divided by the length of the array element ( Number of bytes ). for example pf1 and pf2 Are two pointer variables pointing to the same floating-point array , set up pf1 The value of is 2010H,pf2 The value of is 2000H, And floating-point arrays take up 4 Bytes , therefore pf1-pf2 As the result of the (2000H-2010H)/4=4, Express pf1 and pf2 The difference between 4 Elements . Two pointer variables cannot be added . for example , pf1+pf2 What does that mean ? It doesn't make any sense .

Two pointer variables for relational operation

Two pointer variables pointing to the same array can be used for relational operation to express the relationship between the elements of their index group . for example :
pf1==pf2 Express pf1 and pf2 Point to the same array element
pf1>pf2 Express pf1 In the high address position
pf1<pf2 Express pf2 In the low address position

Pointer variables can also be associated with 0 Compare . set up p Is a pointer variable , be p==0 indicate p Is a null pointer , It doesn't point to any variables ;p!=0 Express p It's not a null pointer . A null pointer is given to a pointer variable 0 Value . for example : #define NULL 0 int *p=NULL; Assign... To a pointer variable 0 Values and no values are different . When the pointer variable is not assigned , It could be any value , It can't be used . Otherwise, it will cause unexpected error . And the pointer variable gives 0 After value , You can use , It just doesn't point to Specific variables .

原网站

版权声明
本文为[Tianshan old demon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211118041419.html