C Language Learning Notes (14) - Pointer Programming

Posted by AliceH on Mon, 03 Jan 2022 20:56:33 +0100

Catalog

14.1 Pointer Overview

14.2 Definition and use of pointer variables

14.2.1 Define pointer variables

14.2.2 Use pointer variables

14.3 Pointer and Array

14.3.1 Pointer and 1-D Array

14.3.2 Pointer and 2-D Array

14.3.3 Pointer and String

14.3.4 Pointer Array

14.4 Pointer as function parameter

14.4.1 Simple pointer variable as function parameter

14.4.2 Pointer to array as function parameter

14.4.3 String pointer as function parameter

14.4.4 Pointer array as function parameter

14.4.5 Use the main() function with parameters

14.5 Pointer Function

14.1 Pointer Overview

  • Pointer

For each variable, the computer specifies a section of memory to store the value of the variable. The starting address of the memory used by a variable is called the address of the variable, and the variable that stores the address is called a pointer variable, or simply a pointer. Simply put, a pointer is the address of a variable.

  • Pointer variable

The so-called pointer variable is a kind of variable designed to hold the pointer. Its value is the address of other variables. Pointer variables are variables that point to other variables. Pointer variables provide access to other variables.

  • Direct access to data

Direct access to data refers to the direct use of variable data through variable names, which is the way we used to write programs to access data. For example:

int i;
scanf("%d",&i);
printf("%d",i);
  • Indirect access to data

Indirect access to data refers to accessing other variable data through pointer variables, which is a data access method widely used in C language.

Pointer variables can point to any data type, such as a basic type, an array, a structure, and so on. Therefore, any type of data can be accessed indirectly through pointer variables.

14.2 Definition and use of pointer variables

Like other variables, pointer variables must be defined before they can be used. The method of defining and using pointer variables is now detailed.

14.2.1 Define pointer variables

The general definition format is as follows:
Data Type * Pointer Variable Name 1, * Pointer Variable Name 2;

Explain:
(1) The'*'in front of the variable name is a symbol of a pointer-type variable and cannot be omitted from the definition.
(2) "Data type" refers to the data type that the pointer variable points to. For example, the following statement defines a pointer variable p to an integer variable and a pointer variable q to a real variable, respectively.
        int *p ;
        float *q;
(3) Variables of other types are allowed to be defined in the same statement as pointer variables. For example: int m,n,*p,*q;

14.2.2 Use pointer variables

  • Initialization of pointer variables

The initialization of a pointer variable is to assign an initial value to it while defining it. Since pointer variables are pointer types, the initial value assigned should be an address value. The general format is as follows:
Data Type * Pointer Variable Name 1 = Address 1, * Pointer Variable Name 2 = Address 2,;

Among them, there are many forms of address representation, such as & variable name, array name, other pointer variables, and so on. For ex amp le:
        int m;
        int *p=&m;
        char string[20];
        char *str=string; 

Explain:
(1) The pointer cannot be initialized with an undefined variable.
(2) When an initial value is assigned to a pointer variable by the address of a variable, the data type of the variable must be the same as the data type that the pointer variable points to.
(3) Except 0, other integers are generally not assigned to pointer variables as initial values. The address of a variable in a program is assigned by the computer, and when an integer is used to assign an initial value to a pointer variable, unexpected consequences may occur. When 0 is used to initialize a pointer variable, the system initializes the pointer variable to a null pointer and does not point to any target. A null pointer in C can also be represented by NULL, which is a macro defined in the header file "studio.h".

  • Assignment of pointer variable

Assignment operations can be used to assign pointer variables during program execution. The general format is as follows:
Pointer variable = address; (

For example:
int m=196,*p,*q;
P=&m; /* Assigns the address of the variable m to the pointer variable p */
q=p; /* Assign a value to the pointer variable q using the pointer variable p*/

  • Entering data using pointer variables

When the pointer variable has a clear pointer. You can use this pointer variable to enter data for the target you are pointing to.

For example:
int score,*p;
p=&score;
scanf("%d",p);
The function of the scanf statement in this section is equivalent to the following statement:
scanf("%d",&score);

  • Pointer Operators and Target Access

For pointer variables, the pointing operation'*'is used when accessing the target to which they point. The general format is: *Pointer variable
For example, the following statement outputs the value of the above variable score:
printf("%d",*p); //*p denotes the target score to which p is pointing. The statement is in conjunction with "printf("%d",score);" Statement Equivalence

The pointer operator in C language is the'*'operator, which has two functions: when defining a pointer, its function is to illustrate a pointer variable; When using pointer operations, it represents the value of the cell to which the pointer is pointing.

The'&'operator is an address operator that takes the address of a subsequent variable, and the'&variable name' can also be directly understood as the address of a variable. (

  • Examples of pointer operations

Enter two integers, a and b, and output them in the order of large and small. The procedure is as follows:

void main(void)
{
    int *p1,*p2,*p,a,b;
    scanf("%d,%d",&a,&b);
    p1=&a;
    p2=&b;
    if(a<b)
    { 
        p=p1; 
        p1=p2; 
        p2=p; 
    } /* Swap Pointer Value */
    printf("a=%d,b=%d\n",a,b);
    printf("Max=%d,Min=%d\n",*p1,*p2);
}

14.3 Pointer and Array

14.3.1 Pointer and 1-D Array

  • The relationship between pointers and one-dimensional arrays

When one-dimensional arrays are stored in memory, the first element occupies storage space continuously. Therefore, for a one-dimensional array a of length N, when pointer p is used to point to its first element, the elements of the array can be accessed through pointer p. The corresponding relationship between pointer p and each element is shown in the following figure.

If the a array is of simple type, a[0] can be represented by'*p', a[1] by'*(p+1)', and'*(p+i)'for any element a[i].

  • Define and use pointer variables to one-dimensional arrays

We can define pointer variables to one-dimensional arrays in the following ways:
int a[6]={10,20,30,40,50,60};
int *p=a;// Array name represents the first address of the array
Or:
int *p=&a[0];

The array elements are referenced by pointer p as follows:
(1) For the first element, the pointer to it is p+i, and the array element is expressed as * (p+i).
(3) Array elements can be represented by pointer variables with subscripts, and p[i] is equivalent to arr[i] and * (p+i).

Explain:
(1) When pointing at an array element with a pointer, it is only related to the element ordinal number, regardless of the number of storage units occupied by each array element, that is, for any type of one-dimensional array arr, when the pointer variable p is assigned with arr (or &arr[0]), the following expression is true: p+i=&arr[i]
(2) It is important to note that when defining a pointer variable to an array, the data type of the pointer variable should be the same as the data type of the array.

  • Program example

(1) Implement input and output of one-dimensional array with pointer.

//Program 1
void main()
{
    int a[10];
    int *p=a, i;
    for(i=0;i<10;i++)
        scanf("%d",p+i);
    for(i=0;i<10;i++)
        printf("%d ",*p++);
}

//Program 2
void main()
{
    int a[10];
    int *p=a, i;
    for(i=0;i<10;i++)
        scanf("%d",p++);
    p=a;
    for(i=0;i<10;i++)
        printf("%d ",*(p+i));
}

//Program 3
void main()
{
    int a[10];
    int *p;
    for(p=a;p<(a+10);p++)
        scanf("%d",p);
    for(p=a;p<(a+10);p++)
        printf("%d ",*p);
}

//Program 4
main()
{
    int i,a[10];
    for(i=0;i<10;i++)
        scanf("%d",a+i);
    for(i=0;i<10;i++)
        printf("%d",*(a+i));
}

(2) Write a sorting program for one-dimensional arrays with pointers, where sorting data is generated by random number functions.

#define N 10
#include"stdlib.h"
void main()
{ 
    int a[N],i,j,temp,*p;
    printf("data:  ");
    for(p=a;p<a+N;p++)  
    {
        *p=rand()%100;
        printf("%4d",*p);
    }
    for(i=1;i<N;i++)
        for(p=a;p<a+N-i;p++) 
            if(*p>*(p+1))
            { 
                temp=*p;
                *p=*(p+1);
                *(p+1)=temp;
            }
    printf("\nresult:");
    for(p=a;p<a+N;p++)
         printf("%4d",*p);
    printf("\n");
}

14.3.2 Pointer and 2-D Array

  • The relationship between pointers and two-dimensional arrays

We know that when a two-dimensional array is stored in a computer, it is stored in the order of row after column. When each row is considered as a whole, that is, as a large array element, the stored two-dimensional array becomes a one-dimensional array. Each large array element corresponds to a row of a two-dimensional array, which we call a row array element. Obviously, each row array element is a one-dimensional array. Therefore, when a two-dimensional array is viewed from the perspective of a two-level array, an M × A two-dimensional array of N can be decomposed into two-dimensional arrays as shown.

Set p to be a pointer variable to array a if "p=a[0];". p+j then points to the element a[0][j] in the a[0] array.
Since each row array such as a[0], a[1] a[M-1] is stored consecutively in turn, for any element a[i][j] in the a array, the pointer p+i*N+j will point to the corresponding pointer for the element a[i][j] as: * (p+i*N+j). Similarly, a[i][j] can be represented by a pointer subscript: p[i*N+j].

  • Addressing array elements with two-dimensional array names

For two-dimensional array a, its a[0] array is pointed by a, its a[1] array is pointed by a+1, its a[2] array is pointed by a+2, and so on. Therefore, *a is equivalent to a[0], *(a+1) is equivalent to a[1], *(a+2) is equivalent to a[2],, that is, for an array of a[i], it is pointed at by *(a+i). Thus, for the array element a[i][j], the array name a is expressed as: *(*(a+i)+j), and the pointer to the element is: *(a+i)+j

Explain:
For two-dimensional array a, although a[0] and a are both the first addresses of the array, they point to different objects:
(1) a[0] is a one-dimensional array name that represents the address of the first element of a[0] array, and'*'is computed to get an array element value, that is, the first element value of a[0] array, so *a[0]==a[0]==*(*a).
(2) A is a two-dimensional array name, which is composed of a[0], a[1], a[2]...m row array elements, a represents the address of the first row array element, its pointer moving unit is "row", so a+i points to the row array i, that is, to a[i]. The'*'operation on a yields the first address of the one-dimensional array a[0], i.e. *a==a[0]==&a[0][0].

  • Program example

Find the maximum value of a two-dimensional array element.

This problem can be solved by simply traversing the array elements. Therefore, you can move the array pointer sequentially. The procedure is as follows:

void main()
{
    int a[3][4]={{3,17,8,11},{66,7,8,19},{12,88,7,16}};
    int *p,max;
    for(p=a[0],max=*p;p<a[0]+12;p++)
        if(*p>max)
            max=*p;
    printf("MAX=%d\n",max);
}

14.3.3 Pointer and String

  • Using character pointers to process strings

There are two ways to process strings: one is to use character arrays to process strings, which have been specially introduced before. Another method is to use character pointers to process strings, which is a more common method in C. It first points to the string with a character pointer in a certain way, and then accesses the string storage area with a character pointer, thereby operating on the string.

There are usually two ways to point a character pointer to a string:
(1) Initialize the pointer string by defining the pointer variable. For example:
        char *p="a string";
"A string" is a string constant that is stored in a memory region of the computer. Initializing the character pointer variable p with this string assigns the address of the first character of the string to P.
(2) Use assignment statements to point pointer variables to strings. For example:
        char ch[20],*s;
        char *str1=ch,*str2;
        s="string";
        str2=str1; 

  • Program example

Copy string with pointer. The procedure is as follows:

void main()
{
    char a[]="I am a student.";
    char b[30],*p1,*p2;
    int i;
    for(p1=a,p2=b;*p1!='\0';p1++,p2++)
        *p2=*p1;
    *p2='\0';
    printf("string a is: %s\n",a);
    printf("string b is: ");
    for(i=0;b[i]!='\0';i++)
        printf("%c",b[i]);
    printf("\n");
}

14.3.4 Pointer Array

  • Definition of one-dimensional pointer array

Array elements that are pointer-type arrays are called pointer arrays, and each element in the pointer array is a pointer variable that points to the same type of data.

The definition of a one-dimensional pointer array is as follows:
Data Type * Array Name [Array Length];
For example:
char *days[7]; // The statement defines a character pointer array named days, which has seven pointer variables to character data, that is, it can store seven pointers.

Like other arrays, pointer arrays can be initialized at definition time or assigned pointer values through assignment statements. Since each element of a pointer array is a pointer variable and can only store address values, when assigning an initial value to a pointer array pointing to a string, assign the first address of the string to the corresponding element of the pointer array.
For example:
Char*days[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};// After initialization, each element of days points to a string, and the element value is the first address of the corresponding string.

  • Program example

Branch outputs seven strings pointed to by the days array. The procedure is as follows:

#include "stdio.h"
void main()
{
    int i;
    char *days[7]={"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday"};
    for(i=0;i<7;i++)
        puts(days[i]);
}

14.4 Pointer as function parameter

Pointers can point to any type of data, so any type of data processing can be done with them. Functions use pointer parameters to enable them to process various types of data. The biggest difference between a function parameter and a variable of the basic data type is that the value of the variable is not passed between the functions, but the address of the variable, so that the data pointed to by the argument pointer can be processed directly by the function.

14.4.1 Simple pointer variable as function parameter

As a function parameter, simple variable pointer is the most basic content of function parameter, which can transfer the address of simple variable to function.

swap() function is used to exchange the values of two variables. The procedure is as follows:

void swap(int *p1,int *p2) 
{ 
    int temp;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
}

void main()
{ 
    int x,y;
    scanf("%d,%d",&x,&y);
    if(x<y)
        swap(&x,&y); //Swap the values of variables x and y. Note that this must be an address, and if data is used, there will be no exchange results
    printf("%d,%d\n",x,y);
}

14.4.2 Pointer to array as function parameter

Since the array name is the first address of the array, it has some of the same properties as the pointer. Therefore, there are many similarities between using a pointer to an array as a function parameter and using an array name as a function parameter.

Examples of related programs are given:

(1) Find the maximum element value of a one-dimensional array.
We use three functions to implement this program: input() to create an array; Using max_a() function to maximize; Use the main() function as the primary tone function. To facilitate writing a function, the array length is assumed to be n, and the pointer p points to the array.

void input(int *p,int n)
{
    int i;
    for(i=0;i<n;i++)
        scanf("%d",p+i); 
    return;
}

int max_a(int *p,int n) 
{ 
    int i,max=*p; 
    for(i=1;i<n;i++)
        if(*(p+i)>max)
            max=*(p+i);
    return(max);
}

void main()
{
    int a[10];
    input(a,10); 
    printf("MAX=%d\n",max_a(a,10));
}

(2) Sort arrays using the sorting function of one-dimensional arrays.

void p_sort(int *,int ); 
void output(int *,int); 

void main()
{
    int a[10]={3,-5,8,16,7,19,11,6,17,5};
    p_sort(a,10);   
    printf("result: ");
    output(a,10);
}
void p_sort(int *p,int n)
{
    int i,temp,*q;
    for(i=1;i<n;i++)
        for(q=p;q<p+n-1;q++) 
            if(*q>*(q+1))     
            {
                temp=*q; 
                *q=*(q+1);
                *(q+1)=temp; 
            }
}
void output(int *p,int n)
{
    int *q;
    for(q=p;q<p+n;q++)
        printf("%d  ",*q); 
    printf("\n");
}

14.4.3 String pointer as function parameter

There is no essential difference between a string pointer as a function parameter and an array pointer as a function parameter described earlier. All functions pass address values, only the type of pointer pointing to the object is different.

Examples of related programs are given:

Copies one input string to another using a string pointer as a function parameter. The procedure is as follows:

#include "stdio.h"
void main()
{
    void copy_s(char *,char *);  
    char a[20],b[30];
    gets(a);    
    copy_s(a,b); 
    puts(b);  
}
void copy_s(char *str1,char *str2)
{
    while((*str2=*str1)!='\0')
    {
        str1++;
        str2++; 
    }
}

14.4.4 Pointer array as function parameter

The elements of a pointer array are pointer variables that allow the processing of a set of strings. When using pointer arrays as function parameters, you can design generic multi-string operation functions.

Examples of related programs are given:

Output of a set of strings sorted in dictionary order. The procedure is as follows:

#include "stdio.h"
#include "string.h"

void main()
{
    void string_sort(char *[],int);
    void string_out(char *[],int);
    char*days[7]={"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday"};
    string_sort(days,7);
    string_out(days,7);
}

void string_sort(char *string[],int n)
{
    char *temp;
    int i,j;
    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i-1;j++)
        if(strcmp(string[j],string[j+1])>0)
        {
            temp= string [j];
            string [j]= string [j+1];
            string [j+1]=temp;
        }
    }
}

void string_out(char * string [],int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%s  ", string[i]);
}

14.4.5 Use the main() function with parameters

  • concept

An important application of pointer arrays is as a parameter to the main() function, which has the following general form:
main (int argc, char *argv[ ])
Where argc represents the number of command line parameters and argv is an array of pointers to command line parameters.

When running C programs under the operating system, you can pass parameters to the main() function as command line parameters. Command line parameters are in the general form of:
Run File Name Parameter 1 Parameter 2... Parameter n
Separate the run file name from the parameters and each parameter with a space.

The string pointed to by the pointer argv[0] is the name of the running file, the string pointed to by argv[1] is the command line parameter 1, the string pointed to by argv[2] is the command line parameter 2,..., and so on.

  • Program example
#include "stdio.h"
main(int argc,char *argv[])
{
    int i;
    printf("argc=%d\n",argc); //Value of output parameter argc
    for(i=1;i<argc;i++)
       printf("%s\n",argv[i]); //Output individual strings as command line parameters
}

14.5 Pointer Function

Function return values are pointer-type functions called pointer functions. Pointer functions are defined differently from other functions by using the'*'character before the function name. The general format is as follows:
Data Type * Function Name (Formal Parameter Table)
{
Function Body

It is important to note that for pointer functions, the value returned with return must be a pointer value.

Examples of related programs are given:
Finds the longest string in a set and outputs it. The procedure is as follows:

#include "stdio.h"
#include "string.h"
void main()
{
    char *max_lenth(char *[],int); 
    char *p_string[4]={"Sydney2000","Beijing2008","Athens1996","Korea1992"};
    char *p; 
    p=max_lenth(p_string,4)
    puts(p); 
}

char *max_lenth(char *string[],int n)  
{
    int i,posion,max_l;
    posion=0;  
    max_l=strlen(string[0]); 
    for(i=1;i<n;i++)
    if(strlen(string[i])>max_l)
    {
        max_l=strlen(string[i]);
        posion=i;
    }
    return(string[posion]);  
}

Topics: C