Black Horse Programmer _ C Language Foundation Pointer (iii)

Source: Internet
Author: User

Overview

Pointers are the essence of the C language, but many beginners are often not very deep in the concept of pointers, so that after learning to become more and more blurred over time, feel the pointer is difficult to grasp, this article through a simple example to try to explain the pointer clearly, today's focus has several aspects:

1. What is a pointer

2. Arrays and pointers

3. Function pointers

What is a pointer

Variable address variables We call the "pointer variable", simply said that the variable p is stored in the address of variable A, then p can be called a pointer variable, or p points to a. When we visit the A variable is actually the program according to a to obtain a corresponding address, and then to the address of the corresponding storage space to get a value, this way we call "direct reference", and when we get a through p, we first have to convert p to p corresponding storage address, Then according to the address to its corresponding storage space to get the storage content, its content is actually a address, and then according to this address to the corresponding storage space to obtain the corresponding content, this content is a value, this through P find a corresponding address and then the way to become "indirect reference." The storage of A and p is listed here in tabular form to help you understand what it says:

Next, take a look at the pointer assignment

  main.c//  point////  Created by Kenshin Cui on 14-7-05.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#include <stdio.h>int main (int argc, const char * argv[]) {        int a=1;    int *p;    p=&a; You can also assign values directly to pointer variables: int *p=&a;    printf ("Address (a) =%x,address (p) =%x\n", &a,p); Results: Address (a) =5fbff81c,address (p) =5fbff81c    printf ("a=%d,p=%d\n", a,*p);//results: A=1,p=1    *p=2;    printf ("a=%d,*p=%d\n", a,*p); Results: a=2,p=2        int b=8;    Char c= 1;    int *q=&c;    printf ("Address (b) =%x,address (c) =%x\n", &b,&c);//Results:    printf ("c=%d,q=%d\n", C, *q);//Results: c=1,q= 2049, why is the value of Q not 1?        return 0;}

Two points need to be explained:

A. int *p; * just means that the p variable is a pointer variable; while printing *p, the * is an operator in *p, which represents the storage space of the variable that the P pointer points to (the current storage is 1), and we also see *p==a; modified *p that modifies the contents of the storage space that P points to. Also modified A, so the second time printing a=2;

B. The type that the pointer points to must be the same type that was declared when the pointer was defined, the pointer q is defined as int and pointed to the char type, and the result output *q printed 2049 for the specific reason (assuming that the pointer length is 2 bytes under the 16-bit compiler)

Because the local variables are stored in the stack, so storage B and then storage A, p, when printing *p, in fact, the address corresponding to the P point of the space to start taking two bytes of data (because the definition of P when it points to the int type, in the 16-bit compiler, the length of int is 2), Exactly defined B and C spaces are contiguous, so take one of the bytes of B, the last *p binary is stored as "0000100000000001" (see Yellow background content), the decimal means is 2049;

c. A pointer variable occupies a space that is independent of the type of variable it points to, and is only related to the number of compiler bits (accurately speaking only with addressing methods);

Arrays and Pointers

Since the storage of the array is contiguous, the array name is the address of the array, so that the array and pointer have a very subtle relationship, first look at the following example:

main.c//point////Created by Kenshin Cui on 14-7-05.//Copyright (c) 2014 Kenshin Cui. All rights reserved.//#include <stdio.h>void changevalue (int a[]) {a[0]=2;} void changeValue2 (int *p) {p[0]=3;}    int main (int argc, const char * argv[]) {int a[]={1,2,3}; int *p=&a[0];        Equivalent to: *p=a; printf ("len=%lu\n", sizeof (int));//Gets an int length of 2//pointer plus 1 for the address backwards to nudge the length of the type (where the type is int, length 2)///i.e. P points to a[0],p+1 pointing to a[1], and so on,        So we can also take out the array element for (int i=0;i<3;++i) {//printf ("a[%d]=%d\n", I,a[i]) via pointers;    printf ("a[%d]=%d\n", i,* (P+i));//Because A is the address of an array, it can also be written as * (A+i), but note that this * (P+i) can be written as * (p++), but * (A+i) cannot be written as * (a++), because the array name is a constant }/* Output result: a[0]=1 a[1]=2 a[2]=3 */ChangeValue (P);    Equivalent to: ChangeValue (a) for (int i=0;i<3;++i) {printf ("a[%d]=%d\n", I,a[i]); }/* Output result: a[0]=2 a[1]=2 a[2]=3 */changeValue2 (a);    Equivalent to: ChangeValue2 (p) for (int i=0;i<3;++i) {printf ("a[%d]=%d\n", I,a[i]);    }/* Output results: A[0]=3 a[1]=2 a[2]=3 */return 0;} 

From the above example we can draw the following conclusions:

    1. Array name a==&a[0]==*p;
    2. If p points to an array, then p+1 points to the next element of the array, noting that the length of the p+1 movement is not fixed, depending on the type of data the P points to;
    3. The pointer can be written in p++ form, but the array name is not possible because the array name is a constant
    4. An argument can use an array name or pointer regardless of the parameter array or pointer of the function;
extensions--strings and pointers

Since strings are character arrays in C, here's a look at the string and array relationships:

  main.c//  point////  Created by Kenshin on 14-7-05.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#include <stdio.h>int main (int argc, const char * argv[]) {    char a[]= "Kenshin";    printf ("%x,%s\n", a,a);//Result: 5fbff820,kenshin, the same variable A is the output string or the output address, depending on the format parameter    printf (a);//results: Kenshin    printf ("\ n");        Char b[]= "Kenshin";    char *p=b;    printf ("b=%s,p=%s\n", b,p);//Results: B=kenshin,p=kenshin        //The pointer stores the address, and the array name stores the address, since the character array can represent a string, the pointer to the character can also be It is easier to define a string    char *c= "Kenshin" in the following way, and//equivalent to char c[]= "Kenshin";    printf ("c=%s\n", c); Result: C=kenshin        return 0;}

The comments in the above code are basically clear, and it is important to point out why printf (a) can output strings directly.

Let's take a look at the definition of printf ():int printf (const char * __restrict, ...) __printflike (1, 2);

In fact, printf's parameter requirements are pointers to character types, and in combination with the above example and we said earlier, if the function parameter is a pointer type then you can pass in the function name, so you can correctly output the contents of the string. Similar to the previous article, strcat (), strcpy () and so on.

function Pointers

Before figuring out the function pointer, let's take a look at the function that returns the pointer type data, after all, the pointer type is also the C language data type, the following is a string converted to uppercase characters of the program, for example, In this example, you can see not only a function that returns a pointer type but also a pointer move operation as mentioned earlier:

  main.c//  point////  Created by Kenshin Cui on 14-06-28.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#include <stdio.h>char * toUpper (char *a) {    char *b=a;//retain the original address because the subsequent loop will change the string's original address    int len= ' A '-' a '; Uppercase and lowercase ASCII differential values equal while    (*a!= ') {//characters End If        (*a> ' a ' &&*a< ' Z ') {//If lowercase characters            * (a++)-= Len; *a indicates that the corresponding character of the array (-32 becomes lowercase), the a++ represents a move to the next character        }    }       return B; int main (int argc, const char * argv[]) {    char a[]= "Hello";    Char *p=toupper (a);    printf ("%s\n", p); Result: HELLO    return 0;}

We all know that the function can only have a return value, if you need to return multiple values, what to do, it is very simple, as long as the pointer is passed as a function parameter can be, in the following example we see the pointer as a parameter to pass.

  main.c//  point////  Created by Kenshin Cui on 14-6-28.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#include <stdio.h>int operate (int a,int b,int *c) {    *c=a-b;    return a+b;} int main (int argc, const char * argv[]) {    int a=1,b=2,c,d;    D=operate (A, B, &c);    printf ("a+b=%d,a-b=%d\n", d,c);//Result: A+b=3,a-b=-1    return 0;}

Functions are also stored in memory, and of course the function has a starting address (in fact the function name is the starting address of the function ), here also need to understand the relationship of function pointers. function pointer definition of the form: return value type (* pointer variable name) (parameter 1, parameter 2), get the function pointer in fact we are the equivalent to get this function, the function of the operation can be done by pointers, And with the previous example you can see the pointer as the C language of the data type, as a parameter, as a return value, then of course function pointers can also be used as parameters and return values of functions:

  main.c//  point////  Created by Kenshin Cui on 14-6-28.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#include <stdio.h>int sum (int a,int b) {    return a+b;} int sub (int a,int b) {return a-a    ;} The function pointer is passed as a parameter int operate (int a,int b,int (*p) (Int,int)) {    return P (A, b);} int main (int argc, const char * argv[]) {    int a=1,b=2;    The =sum;//function name of int (*p) (int, int) is the first address, equivalent to: Int (*p) (int,int);p =sum;    int C=p (A, b);    printf ("a+b=%d\n", c); Result: the a+b=3            //function is passed as a parameter    printf ("%d\n", Operate (A, B, sum));//Results: 3    printf ("%d\n", Operate (A, B, sub)); Results: -1        return 0;}

A function pointer can be passed as a function parameter, which is too powerful to remember the delegate in C #. Remember that the C # book often mentions that a delegate is similar to a function pointer, which is actually the case above. It is important to note that the normal pointer can be written as p++ to move, while the function pointer written p++ is meaningless.

Black Horse Programmer _ C Language Foundation Pointer (iii)

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.