Key Excerpt from C language (25 ~ 28 pointer and array)

Source: Internet
Author: User

25. pointer array and array pointer

Array type: arrays in C language have their own specific types.

The array type is determined by the element type and array size. For example, the int array [5] type is int [5], not int.

Define the array type: Rename the array type through typedef -------Typedef type (name) [size];

Array type: typedef int (aint5) [5];

Typedef float (afloat10) [10];

Array definition: aint5 iarray;

Afloat10 farray;

Array pointer: 1. the array pointer is used to point to an array.

2. the array name is the starting address of the first element of the array, but it is not the starting address of the array.

3. You can get the starting address of the array by applying the get URL & to the array name.

4. the array pointer can be defined through the array type: arraytype * pointer;

5. You can also directly define: type (* pointer) [N]; // pointer is the name of the array pointer variable, type is the type of the array to point to, and N is the size of the array to point

# Include <stdio. h> typedef int (aint5) [5]; typedef float (afloat10) [10]; typedef char (achar9) [9]; int main () {aint5 A1; float farray [10]; afloat10 * pF = & farray; achar9 carray; char (* PC) [9] = & carray; char (* pcw) [4] = carray; // The compiler will warn int I = 0; printf ("% d, % d \ n", sizeof (aint5), sizeof (A1); for (I = 0; I <10; I ++ ){(* PF) [I] = I; // array pointer usage} For (I = 0; I <10; I ++) {printf ("% F \ n", farray [I]);} printf ("% 0x, % 0x, % 0x \ n ", & carray, PC + 1, pcw + 1); // PC + 1 <====> (unsigned INT) PC + 1 * sizeof (* PC) // + 9}

Output:

20, 200.0000001.0000002.0000003.0000004.0000005.0000006.0000007.0000008.0000009.00000028FECB, 28FED4, 28FECF

Pointer array: 1. pointer array is a normal Array

2. Each element in the pointer array is a pointer.

3. Definition of array pointer: type * parray [N]; type * indicates the type of each element in the array, parray indicates the array name, and N indicates the array size.

Example:

#include <stdio.h>#include <string.h>int lookup_keyword(const char* key, const char* table[], const int size){    int ret = -1;        int i = 0;        for(i=0; i<size; i++)    {        if( strcmp(key, table[i]) == 0 )        {            ret = i;            break;        }    }        return ret;}#define DIM(a) (sizeof(a)/sizeof(*a))int main(){    const char* keyword[] = {            "do",            "for",            "if",            "register",            "return",            "switch",            "while",            "case",            "static"    };        printf("%d\n", lookup_keyword("return", keyword, DIM(keyword)));    printf("%d\n", lookup_keyword("main", keyword, DIM(keyword)));}

Main function parameters: the main function can be understood as a function called by the operating system. When executing a program, you can pass parameters to the mian function.

There are the following forms:Int main ()

Int main (INT argc)

Int main (INT argc, char * argv [])

Int main (INT argc, char * argv [], char * env [])

26. Multi-dimensional array and multi-dimensional pointer

Pointer to pointer: 1. the pointer is essentially a variable, and there are also value passing and address passing calls.

Example: reset the dynamic space size

 

#include <stdio.h>#include <malloc.h>int reset(char**p, int size, int new_size){    int ret = 1;    int i = 0;    int len = 0;    char* pt = NULL;    char* tmp = NULL;    char* pp = *p;        if( (p != NULL) && (new_size > 0) )    {        pt = (char*)malloc(new_size);                tmp = pt;                len = (size < new_size) ? size : new_size;                for(i=0; i<len; i++)        {            *tmp++ = *pp++;              }                free(*p);        *p = pt;    }    else    {        ret = 0;    }        return ret;}int main(){    char* p = (char*)malloc(5);        printf("%0X\n", p);        if( reset(&p, 5, 3) )    {        printf("%0X\n", p);    }        return 0;}

Two-dimensional array and second-level pointer:

1. Arrange two-dimensional arrays in one-dimensional mode in memory

2. The first dimension in a two-dimensional array is a one-dimensional array.

3. The second dimension in the two-dimensional array is the specific array.

4. the array name of a two-dimensional array can be seen as a constant pointer.

Traverse a two-dimensional array using a one-dimensional array:

# Include <stdio. h> # include <malloc. h> void printarray (int A [], int size) {int I = 0; printf ("printarray: % d \ n", sizeof ()); // The pointer length is printed here for (I = 0; I <size; I ++) {printf ("% d \ n", a [I]);} int main () {int A [3] [3] = {0, 1, 2}, {3, 4, 5}, {6, 7, 8 }}; int * P = & A [0] [0]; printarray (p, 9); Return 0 ;}

Print result:

printArray: 4012345678

Array name:

One-dimensional array name indicates the address of the first element of the array, int A [5] -----> the type of A is int *

The two-dimensional array name also indicates that the first element address of the array is int M [2] [5] -------> the type of M is int (*) [5]

Conclusion: 1. Two-dimensional array names can be seen as constant pointers to arrays.

2. Two-dimensional arrays can be viewed as one-dimensional arrays.

3. Each element in a two-dimensional array is a one-dimensional array of the same type.

#include <stdio.h>int main(){    int a[5][5];    int(*p)[4];        p = a;        printf("%d\n", &p[4][2] - &a[4][2]);}

Output:-4 (The pointer pointing to the same array is subtracted to obtain the subscript difference, instead of the address difference.)

How to dynamically apply for a two-dimensional array:

#include<stdio.h>#include<malloc.h>int** malloc2d(int row,int col){int** ret = (int**)malloc(sizeof(int*) * row);int* p = (int*)malloc(sizeof(int)*row*col);int i = 0;        if( ret && p)   {for(i=0;i<row;i++){ret[i] = (p + i*col);}      }else{  free(ret);  free(p);    ret = NULL;}    return ret;} void free2d(int** a ){free(a[0]);free(a);}

Conclusion: 1. the C language only contains one-dimensional arrays, And the array size must be determined as constants during compilation.

2. the array element in the C language can be any type of data, that is, the element of the array can be another Array

3. in C language, only the size of the array and the address of the first element of the array are determined by the compiler.


27. array parameters and pointer Parameters

Why does the array parameter in C Language degrade to a pointer ??

1. in C language, parameters are transmitted only as value copies.

2. When an array is passed to the function, it is a waste of space and time to copy the entire array. Therefore, the array name is treated as a constant pointer and the first address of the array element is passed.


Two-dimensional array parameters also have degradation problems: 1. A two-dimensional array can be considered as a one-dimensional array, and each element in a two-dimensional array is a one-dimensional array.

The first dimension parameter in the two-dimensional array parameter can be omitted.

Void F (int A [5]); <----> void F (int A []) <------> void F (int *)

Void g (int A [3] [3]) <----> void g (int A [] [3]) <----> void g (INT (*) [3])

Degradation equivalence relationship:


Note: 1. the C language cannot pass any multi-dimensional array to a function.

2. To provide correct pointer operations, all dimension lengths except the first dimension must be provided.

Restriction: one-dimensional array parameter ------ A length information must be provided to identify the end position of the array

Two-dimensional array parameters ------ cannot be passed directly to the Function

3D or multi-dimensional array parameters ------ cannot be used

Example:

# Include <stdio. h> void access (int A [] [3], int row) {int Col = sizeof (* A)/sizeof (INT); * A is an array, evaluate the number of * A elements: 3 int I = 0; Int J = 0; printf ("sizeof (A) = % d \ n", sizeof ()); // pointer length. A is a pointer with a length of 4 bytes for (I = 0; I <row; I ++) {for (j = 0; j <Col; j ++) {printf ("% d \ n", a [I] [J]) ;}} int main () {int A [3] [3] = {0, 1, 2}, {3, 4, 5}, {6, 7, 8}; Access (, 3 );}

Print result:

sizeof(a) = 4012345678

Twenty-eight. Function and Pointer Analysis

Function Type: the return value, parameter type, and number of parameters are jointly determined. For example, the int add (int I, Int J) type is int (INT, INT)

Rename a function type using typedef in C Language

Typedef type name (parameter list)

Example: typedef int F (INT, INT); typedef void P (INT)

Function pointer: A function pointer is used to point to a function. The function name is the entry address of the execution function body.

Define function pointer: functype * pointer;

Similar to an array pointer, you can define it as follows: Type (* pointer) (parameter list)

# Include <stdio. h> typedef int (func) (INT); int test (int I) {return I * I;} void F () {printf ("call f ()... \ n ") ;}int main () {func * PT = test; void (* PF) () = & F; // & optional, the old version of the compiler only supports the & get address operator PF (); // new call (* PF) (); // old-fashioned call, with the same effect as printf ("function pointer call: % d \ n ", Pt (2 ));}

Output result:

Call f()...Call f()...Function pointer call: 4

Callback Function: A Call mechanism implemented by using function pointers.

Principle: 1. The caller does not know the specific function to be called when a specific event occurs.

2. The called function does not know when it will be called, but only the task to be completed after it is called.

3. When a specific event occurs, the caller calls a specific function through the function pointer.

The callback mechanism separates the caller and the called function. The two are independent from each other and can be modularized when writing large software.

#include <stdio.h>typedef int(*FUNCTION)(int);int g(int n, FUNCTION f){    int i = 0;    int ret = 0;        for(i=1; i<=n; i++)    {        ret += i*f(i);    }        return ret;}int f1(int x){    return x + 1;}int f2(int x){    return 2*x - 1;}int f3(int x){    return -x;}int main(){    printf("x * f1(x): %d\n", g(3, f1));    printf("x * f2(x): %d\n", g(3, f2));    printf("x * f3(x): %d\n", g(3, f3));}

Pointer reading skills:

Right-left rule: 1. Starting from the undefined identifier in the parentheses in the innermost layer

2. First look to the right and then to the left

3. When you encounter parentheses or square brackets, you can determine the part type and adjust the direction.

4. Repeat steps 2 and 3 until the reading is complete.

For example: int (* func) (int *); * func this is a pointer to a function with the int type (int *)

# Include <stdio. h> int main () {int (* P2) (int *, INT (* f) (int *); // * P2 pointer, pointing to int (int *, INT (* f) (int *) function int (* P3 [5]) (int *); // [] level high, so P3 is first an array of 5 elements, and then take out P3 [5]. We can see that the element is a pointer and points to int (int *) int (* P4) [5]) (int *); (* P4) Pointer --> int (* [5]) (int *) --> point to array [5] --> int (*) (int *) --> the array type is the function pointer pointing to int (int *) int (* P5) (int *) [5]; // (* P5) pointer-> int (* (int *) [5]-> point to function (int *)-> function return value is-> int (*) [5]}

The trick is: Take one after Parsing



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.