A pointer variable definition
type *name;
Here, '*' to represent him is a pointer variable.
Second, the pointer assignment
int *p=nullptr;
Here, nullptr is a null pointer
int a=2;
p=&a;
'&' Character to take the address (which is often used in scanf) to pass a pointer to the address p, where a must int. Obviously, the p-direct access, the address operation. If the operation must be added to the indirect pointer operator '*'.
note!
1, can not assign a pointer variable number
2, the pointer variable can not add '*' address when want to change
3, printf ( "% d", p); output the address pointer, and printf ( "% d", * p); pointer value is output
Pointer variable with ordinary variables, and assignment to be defined before use. As defined int a; int * p = & a; then, P is stored in the starting address of a occupied cells, * p and a are the same, so printf ( "% d", * p); equal to printf ( "% d", a);
Example 1
problem B + A (pointer Edition)
#include <cstdio> the using namespace STD; int main () { int A, B, P1 *, P2 *; // declaration of a general variable and pointer P1 = & A; // pointer variable assignment P2 = & B; Scanf ( " % % D D " , P1, p2); // P1 and p2 are directly stored address, the addresses do not have to take the printf ( " % D " , * * P1 + p2); // fetch address by adding the contents of return 0 ; }
Third, the addition and subtraction pointer variable
Pointer only supports two modes of operation! + And -, and the general operation of the array with
Example 2
Tao Tao picking apples (pointer version)
Title Description https://www.luogu.org/problemnew/show/P1046
#include <cstdio> the using namespace STD; int A [ 10 ]; int main () { int I, H, SUM, * P; // declare variables for (I = 0 ; I < 10 ; I ++ ) Scanf ( " % D " , A & [I]); // loop input Scanf ( " % D " , & H); // input itself height H + = 30 ; // plus stool height SUM = 0 ; // Apple can pick the total number p A =; //a is the array a first address for (I = 0 ; I < 10 ; I ++ ) { IF (* P <= H) // determines whether to pick SUM ++; // able to pick + 1'd P ++; // this p ++ is not a memory address at +1, but + sizeof (int) (to see him what type of pointer variable, if it is double plus sizeof (double)) } printf ( " % d " , SUM); // output Total return 0 ;
}
We can see, p ++ refers to an integer after arrival. Thus be obtained: p-- before arrival is an integer, p = p + 3 is an integer of 3 to move backward, and the (p + 3) is the address of the third integer later.