指针入门

  • & produces the address of its operand:
    • For example, in the following statements an integer variable and a pointer to an integer variable are declared.

Then, the address of the variable a is determined with the & operator and is assigned to the pointer variable.

1 int a, *P; 

2 P = &a;    //'&' produces the address of 'a' and assigns to pointer variable 'p'.
  • * is the indirection operator and is used with pointers to access the value being pointed to:

expression '*p' access the value of variable 'a',so we treat '*p' as 'a' at any situation.

1 int a = 1;

2 int * p = &a;   //variable 'p' points to the address of 'a'.

3 *p = 3 - *p;    //because '*p' indirectly access 'a', variable 'a' will be changed by this statement.

4 printf("*p=%d\n", *p);  //*p=2

5 printf("a=%d\n", a);    //a=2
  • The expression
    *&a = 25;

    is equal to

    a = 25;

    it assigns the value 25 to the variable 'a':

    • First, the & operator generates the address where the variable 'a' is stored, which is a pointer constant.
      (Note that it is not necessary to know the actual value of the constant in order to use it.)
      Then, the * operator goes to the location whose address is given as the operand.  In this expression, the operand is the address of 'a', so the value 25 is stored in 'a'.
  • the size Integer and floating number store in memory are the same, for example,in a 16-bit operating system,

  and the bellowing segment codes, variable 'r' is an integer and store the address of variable 'f'

1 float f = 3.14;

2 float * r = &f;    //pointer 'r' store the address of variable 'f'.

 

你可能感兴趣的:(入门)