C language learning basics (5) pointer

Source: Internet
Author: User

C language learning basics (5) pointer
Direct reference

Char;

A = 10;

How is the program operated internally?

In fact, the program reads and writes data to or out of the bucket where the variable is stored. For the above Code,

The system automatically converts variable name a to the storage address of the variable, and finds the storage space of variable a based on the address, then, data 10 is put into the bucket of variable a in a binary format.

When a variable is referenced by a variable name, the system automatically converts the variable name to its storage address.


Indirect reference

For example, store the address of variable a in another variable, for example, in variable B, and indirectly reference variable a through variable B to indirectly read and write the value of variable. This is "indirect reference"

To sum up, the variable used to store the variable address is called "pointer variable ". In the above case, variable B is a "pointer variable". We can say that pointer variable B points to variable.

Pointer Definition

General format:Class name identifier*Pointer variable name;

Int * p;

Float * q;

  • "*" Is a specifier used to indicate that this variable is a pointer variable and cannot be omitted, but it is not part of the variable name.
  • The previous type identifier indicates the type of the variable pointed to by the pointer variable, and can only point to the initialization of this type of variable pointer

    Int a = 10; int * p = & a; float B = 2.3f; float * q; q = & B;


    The pointer operator assigns a value to the variable pointed to by the pointer.

    Char a = 10;

    Printf ("value of a before modification: % d \ n", );


    // Pointer Variable p points to variable

    Char * p = & a; // This * specifies the pointer description.


    // Indirectly modify the value of variable a through the pointer Variable p

    * P = 9; // This * is a pointer operator that assigns 9 to the address a pointed to by the pointer, which is equivalent to a = 9;

    // Here, the value of a is indirectly modified.

    Printf ("value of a after modification: % d", );

    Obtains the value of the variable pointed to by the pointer.

    Char a = 10;

    Char * p;

    P = &;


    Char value = * p; // access the corresponding bucket based on the p value (that is, the address of variable a), obtain the stored content (that is, retrieve the value of variable a), and assign the value to the value.

    Printf ("Get a value: % d", value );

    Usage notes

    Do not assign values to the content indicated by the pointer variable before it points to a fixed address. The following statements are incorrect.


    Int * p;

    * P = 10; // This is incorrect.

    Assign a value after the pointer variable points to a fixed variable. The following statements are correct.

    // Define two int Variables

    Int a = 6, B;


    // Define a pointer Variable p pointing to variable B

    Int * p;

    P = & B;


    // Assign the value of a to variable B

    * P =;

    Example

    Swap the address of two character variables (change the value of the real parameter)

    Void swap (char * p, char * q)

    {

    Char temp = * p;

    * P = * q;

    * Q = temp;

    }


    Int main (int argc, constchar * argv [])

    {

    Char a = 'A', B = '&';

    Swap (& a, & B );

    Printf ("a = % c B = % c \ n", a, B );

    }

    Point an element to a one-dimensional array with a pointer

    Int a [2] = {2, 3}; int * p = & a [0]; * p = 10; then a [0] should be equal to 10

    The address of array name a is the same as the address of its first element, so p = & a [0] has the same effect as p =

    Pointers to traverse array elements

    Int ary [] = {1, 2, 4, 5 };

    Int * q = ary;

    For (int I = 0; I <5; I ++)

    {

    // The Element Memory Address in the array is a continuous storage method. When the pointer moves a corresponding type in bytes (int, char...), it points to the next element value.

    // Printf ("number: % d", * (q + I); // move the address

    // Printf ("number: % d", * (ary + I); // move the address

    Printf ("number: % d", * (q ++); // q = q + 1, move the pointer to the address

    // Printf ("number: % d", * (ary ++); // The constant cannot be assigned a value.

    }


    Array, pointer, function parameter

    Parameter array, real parameter pointer

    Void change (int B []) {

    B [0] = 10;

    }


    Int main ()

    {

    // Define an array of the int type

    Int a [4] = {1, 2, 3, 4 };

    Int * p =;


    // Pass array name a to the change function

    Change (p );

    // View a [0]

    Printf ("a [0] = % d", a [0]);

    Return 0;

    }

    Parameter pointer, real parameter Array

    Void change (int * B ){

    B [0] = 10;

    // Or * B = 10;

    B [1] = 11;

    // Or * (B + 1) = 11;

    }


    Int main ()

    {

    // Define an array of the int type

    Int a [4] = {1, 2, 3, 4 };


    // Pass array name a to the change function

    Change ();

    // View a [0]

    Printf ("a [0] = % d", a [0]);

    Return 0;

    } // You can see that in many cases, pointers and arrays can be switched to each other. However, pointers are not equal to arrays.


    Use a pointer to traverse all characters in a string

    Char chs [] = "abcde ";

    Char * p;

    P = chs;

    For (; * p! = '\ 0'; p ++)

    {

    Printf ("data: % c", * p );

    }

    Printf ("\ n ");


    Direct pointer to string

    Char * p = "abcde ";

    Strlen ("abde ");

    Function declaration in string. h

    Size_t strlen (const char *);

    Char * strcpy (char *, const char *); // string copy Function

    Char * strcat (char *, const char *); // String concatenation Function

    Int strcmp (constchar *, constchar *); // string comparison Function

    Their parameters are pointer types pointing to character variables, so you can pass in Pointer variables or array names.

    Other methods for pointing a pointer to a string

    1 char s [10];

    2 s = "mj"; // the compiler must report the error of Row 3 because s is a constant and represents the first address of the array. Value assignment is not allowed.


    1 char * s = "mj ";

    2

    3 * s = "like ";

    Two errors were made in the 3rd line of code:

  • The 3rd line of code is equivalent to saving the string "like" into the memory space pointed to by s. As can be seen from the 1st line of code, s points to the first character 'M' of "mj ',
  • That is to say, s points to a char-type bucket with only one byte. To store "like" in the space of one byte, the memory must overflow.
  • The Code in line 1st shows that the pointer s points to the String constant "mj "! Therefore, you cannot use pointers to modify the string content!
  • Even if it is * s = 'A' and "It seems correct", it is also wrong, because s points to A constant string and cannot modify its internal characters.


  • Char a [] = "lmj"; defines a string variable! Char * p = a; * p = 'l'; the variable can be changed by pointer, but the constant cannot.
  • Char * p2 = "lmj"; defines a String constant!
    Returns the pointer function.

    The function that returns the pointer is generally in the following format:Type name * function name (parameter list)

    // Convert lowercase letters in the string 'str' into uppercase letters, and return the changed string

    // Note: The parameter here must be a string variable and cannot be a String constant.

    [Plain]View plaincopyprint?
    1. Char * upper (char * str ){
    2. // Retain the original address first. This is because the position indicated by str changes accordingly.
    3. Char * dest = str;
    4. // If not empty characters
    5. While (* str! = '\ 0 '){
    6. // If it is a lowercase letter
    7. If (* str> = 'A' & * str <= 'Z '){
    8. // Change to uppercase letters. There is a fixed difference between the ASCII values of lower case and upper case letters
    9. * Str-= 'a'-'A ';
    10. }
    11. // Traverse the next character
    12. Str ++;
    13. }
    14. // Return a string
    15. Return dest;
    16. }
    17. Int main ()
    18. {
    19. // Define a string variable
    20. Char str [] = "lmj ";
    21. // Call a function
    22. Char * dest = upper (str );
    23. Printf ("% s", dest );
    24. Printf ("% s", str );
    25. Return 0;
    26. }Pointer to function

      The general format of definition:Type of the return value of the function (* pointer variable name) (Form parameter 1, form parameter 2 ,...);

      Note: variable names of formal parameters can be omitted, or even the entire list of formal parameters can be omitted.

      Int sum (int a, int B)

      {

      Return a + B;

      }

      Int main ()

      {

      Int (* q) (int a, int B) = sum; // (int a, int B) can be written as (int a, int) or (int, int) or ()

      Int result = (* q) (); // call the Function

      Printf ("\ n % d", result)

      Return 0;

      }

      Use a function as a parameter

      Void get (int (* q) (int a, char B), float c ){}

Related Article

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.