8 be good at using pointers

Posted by Chrysanthus on Sat, 25 Dec 2021 23:53:40 +0100

Pointer

Since the required variable unit can be found through the address, it can be said that the address points to the variable unit and the address is visualized as a pointer
Through it, you can find the memory unit with its address
The point is represented by an address
Visualize an address as a pointer
If a variable is specially used to store the address of another variable (i.e. pointer), it is called "pointer variable"
The value of the pointer variable is the address

#include<stdio.h>
int main()
{
	int a=100,b=10;
	int *pointer_1,*pointer_2;
	pointer_1 = &a;
	pointer_2 = &b;
	printf("a=%d,b=%d\n",a,b);
	printf("*pointer_1=%d,*pointer_2=%d\n",pointer_1,pointer_2);
	return 0;
}

Defines the general types of pointer variables

Type name * pointer variable name
*Indicates that the type is a pointer variable
The meaning of a variable pointer includes two aspects: one is the pure address represented by the number of the storage unit, and the other is the data type of the storage unit it points to
How to represent pointer types? The type of pointer to integer data type is "int *", which is read as "pointer to int" or "int pointer" for short
Only the address (pointer) can be stored in the pointer variable. Do not assign an integer to the pointer variable

How to reference pointer variables

(1) Assign values to pointer variables
p=&a; // The address of a is assigned to the pointer variable p
(2) The variable pointed to by the reference pointer variable
If P = & A has been executed
Printf(“%d”,*p); // Outputs the value of the variable a pointed to by P as an integer
(3) Reference the value of the pointer variable
Printf(“%o”,p); // If P points to a, the address of a is output, i.e. & A

&Addressing operator

  • Pointer operator (indirect access operator)
#include<stdio.h>
int main()
{
	int *p1,*p2,*p,a,b;
	printf("please enter two integer numbers:");
	scanf("%d,%d",&a,&b);
	p1=&a;
	p2=&b;
	if(a<b)
	{p=p1;p1=p2;p2=p;//p1 = &b;p2=&a;
	}
	printf("a=%d,b=%d\n",a,b);
	printf("max=%d,min=%d\n",*p1,*p2);
	return 0;
}
#include<stdio.h>
int main()
{
	void swap(int *p1,int *p2);
	int *p1,*p2,*p,a,b;
	printf("please enter two integer numbers:");
	scanf("%d,%d",&a,&b);
	p1=&a;
	p2=&b;
	if(a<b)
	{
	//p=p1;p1=p2;p2=p;
	swap(p1,p2);
	}
//	printf("a=%d,b=%d\n",a,b);
	printf("max=%d,min=%d\n",a,b);
	return 0;
}

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

=t;
}

The pointer to the array element is the address of the array element. You can point to an array element with a pointer variable
If there is an array a, then a[i] and * (a+i) are unconditionally equivalent

#include<stdio.h>
int main()
{
	int i,*p,a[10];
	p=a;
	printf("please enter 10 integer numbers:");
	for(i=0;i<10;i++)
	{
		scanf("%d",p++);
	}
	p=a;
	void sort(int x[],int n);
	sort(p,10);
	for(p=a,i=0;i<10;i++)
	{
		printf("%d ",*p);
		p++;
	}
	return 0;
}

void sort(int x[],int n)
{
	int i,j,k,t;
	for(i=0;i<n-1;i++)
	{
		k=i;
		for(j=i+1;j<n;j++)
		{
			if(x[j]>x[k])
			{
				k = j;
			}
			   if(k!=i)
			   {
			   	t = x[i];
			   	x[i]=x[k];
			   	x[k]=t;
			   }
		}
	}
}

(a[i] + j) or (* (a+i) +j) is the value of a[i][j]
*(a+i) and a[i] are equivalent

If a pointer variable pt is used to point to a sub one-dimensional array, it should be defined as follows:
Int(*pt)[4];// Indicates that PT points to a one-dimensional array composed of four integer elements

Precede the pointer to the row with *, indicating that it is converted to a pointer to the column
Adding & before the pointer to the column is called the pointer to the row
For ex amp le, a[0] is an element pointing to 0 rows and 0 columns. Add & to get & a[0], pointing to 0 rows of a two-dimensional array

#include<stdio.h>
int main()
{
	int a[3][4] = {1,3,5,7,9,2,4,6,8,10,11,12};
	int *p;
	//int i;
	for(p = a[0];p<a[0]+12;p++)
	{
		if((p-a[0] )%4 == 0)
		{
			printf("\n");
		}
		printf("%4d ",*p);
	}
	printf("\n");
    printf("%d",*(p+(1*4+2)));
	return 0;
}

(1) Pointer variable to array element
The formula for calculating the relative position of a[i][j] in the two-dimensional array is im+j
Where m is the number of columns of the two-dimensional array (the size of the two-dimensional array is nm)
If the pointer variable p points to a [0] [0] at the beginning, the address of a [i] [J] is & A [0] [0] + (IM + J) or p+(im+j)
(2) Pointer variable to a one-dimensional array of m elements

#include<stdio.h>
int main()
{
	int a[3][4] = {1,3,5,7,9,2,4,6,8,10,11,12};
	int (*p)[4],i,j;//The pointer variable p points to a one-dimensional array containing four integer elements
	p=a;//p points to row 0 of the two-dimensional array
	scanf("%d%d",&i,&j);
	printf("a[%d][%d]=%d\n",i,j,*(*(p+i)+j));
	return 0; 
}

Int a[4];//a has four elements, each of which is an integer
Int (*p)[4];//(*p) has four elements, each of which is an integer

Multidimensional arrays can also be used as function parameters. Use a pointer variable as a formal parameter to accept the address passed from the array name of the argument. There are two methods: 1 Use a pointer to the variable 2 Using pointer variables pointing to one-dimensional arrays

#include<stdio.h>
int main()
{
	float score[3][4] = {{65,57,70,60},{80,87,90,81},{90,99,100,98}};
	void average(float *p,int n);
	average(*score,12);
	void search(float (*p)[4],int n);
	search(score,2);//Find the grade of the student with serial number 2
	void search2(float(*p)[4],int n);
	search2(score,2);
	return 0; 
}
void average(float *p,int n)
{
	float *p_end;
	float sum =0,aver;
	p_end = p+n-1;
	for(;p<=p_end;p++)
	{
		sum = sum +(*p);
	}
	aver = sum /n;
	printf("average = %5.2f\n",aver);
}
void search(float (*p)[4],int n)
{
	int i;
	printf("The score of NO.%d are:\n",n);
	for(i=0;i<4;i++)
	{
		printf("%5.1f ",*(*(p+n) +i));
	}
	printf("\n");
}
void search2(float(*p)[4],int n)
{
	int i,j,flag;
	for(j=0;j<n;j++)
	{
		flag = 0;
		for(i=0;i<4;i++)
		{
			if(*(*(p+j)+i)<60)
			{
				flag =1;
			}
		}
		if(flag == 1)
		{
			printf("%d\n",j+1);
			for(i=0;i<4;i++)
			{
				printf("%5.1f ",*(*(p+j)+i));
			}
		    printf("\n");
		}
	}
}

Reference string through pointer

Reference method of string
(1) Use a character array to store a string. You can refer to a character in the string through the array name and subscript, or output the string through the array name and format declaration "% s"
Printf("%s",string);
(2) Use the character pointer variable to point to a string constant, and use the character pointer variable to reference the string constant
#include<stdio.h>
int main()
{
char *string = "I love China!";
printf("%s\n",string);
return 0;
}
char *string = "I love China!";
Equivalent to
Char *string;
String = "I love China!";
A string can be output through the character array name or character pointer variable. For a numeric array, you cannot attempt to output all its elements with the array name

Copy string a to string b

#include<stdio.h>
int main()
{
	char a[] = "I love China!",b[20];
	int i;
	for(i=0;*(a+i)!='\0';i++)
	{
		*(b+i) = *(a+i);
	}
	*(b+i) = '\0';
	printf("%s\n",a);
	for(i=0;*(b+i) != '\0';i++)
	{
		printf("%c",*(b+i));
	}
	return 0; 
}
Do it with pointer variables
#include<stdio.h>
int main()
{
	char a[] = "I love China!",b[20],*p1,*p2;
	p1=a,p2=b;
	for(; *p1 != '\0';p1++,p2++)
	{
		*p2 = *p1;
	}
	*p2  = '\0';
	printf("%s\n",b);
	return 0; 
}

Character pointer as function parameter
If you want to "pass" a string from one function to another, you can use the address passing method, that is, use the character array name as the parameter, or use the character pointer variable as the parameter. The content of the string can be changed in the called function, and the changed string can be referenced in the calling function

Copy string with function

#include<stdio.h>
int main()
{
	char a[] = "I love China!";
	char b[]="I am a student!";
	printf("%s %s\n",a,b);
	void copy_string(char from[],char to[]);
	copy_string(a,b);
	printf("%s %s\n",a,b);
	
	return 0; 
}
void copy_string(char from[],char to[])
{
	int i=0;
	while(from[i] != '\0')
	{
		to[i]=from[i];
		i++;
	}
	to[i] = '\0';
}

Using character pointer variables as formal parameters

#include<stdio.h>
int main()
{
	char a[] = "I love China!";
	char b[]="I am a student!";
	printf("%s %s\n",a,b);
	char *from =a,*to=b;//
	void copy_string(char from[],char to[]);
	copy_string(from,to);//
	printf("%s %s\n",a,b);
	return 0; 
}
void copy_string(char from[],char to[])
{
	int i=0;
	while(from[i] != '\0')
	{
		to[i]=from[i];
		i++;
	}
	to[i] = '\0';
}

Using character pointer variables as formal parameters and arguments

#include<stdio.h>
int main()
{
	char *a = "I love China!";
	   char b[]="I am a student!";
	printf("%s %s\n",a,b);
	char *p = b;
	char *from =a,*to=b;//
	void copy_string(char from[],char to[]);
	copy_string(a,p);//
	printf("%s %s\n",a,b);
	return 0; 
}
void copy_string(char *from,char *to)
{
	for(;*from != '\0';from++,to++)
	{
		*to = *from;
	}
	*to = '\0';
}

Use character pointer variables and character arrays for comparison

(1) The character array consists of several elements, one character is placed in each element, and the address (the address of the first character in the string) is stored in the character pointer variable. It is never to put the character in the character pointer variable
(2) Assignment method. You can assign values to character pointer variables, but not array names
(3) Initialization meaning
(4) Storage unit when compiling, several storage units are allocated to the character array to store the values of each element, while only one storage unit is allocated to the character pointer variable
(5) The value of the pointer variable can be changed, while the character array name represents a fixed value (the address of the first element of the array) and cannot be changed
(6) The values of the elements in the character array (a []) can be changed (they can be re assigned), but the contents of the string constant pointed to by the character pointer variable (* b) cannot be replaced (they cannot be re assigned)
(7) Reference array element
A[5] = *(a+5);
If int *p = a;
P[5] = *(p+5) = a[5];
(8) A pointer variable is used to point to a format string, which can be used instead of the format string in the printf function
Char *format;
Format = "a = %d,b=%f\n";
Printf(format,a,b);
amount to
Printf("a = %d,b=%f\n",a,b);
This printf function is called a variable format output function
However, when using a character array, you can only initialize or copy the elements one by one when defining the array, rather than assign a value to the whole array with an assignment statement

Pointer to function

The function name represents the starting address of the function. When calling the function, get the starting address of the function from the function name and execute the function code
Call a function, which can be called by function name and pointer variable pointing to the function
(1) Call function by function name

#include<stdio.h>
int main()
{
	int a,b,c;
	scanf("%d%d",&a,&b);
	int max(int x,int y);
	c =max(a,b);
	printf("max = %d\n",c);
	return 0;
}
int max(int x,int y)
{
	int z;
	if(x>y)
	{
		z=x;
	}
	else
	{
		z=y;
	 } 
	return z;
}

(2) Call the function it points to through the pointer variable
There's a problem

#include<stdio.h>
int main()
{
	int max(int,int);
	int (*p)(int,int);
	int a,b,c;
	p = max;
	scanf("%d,%d",&a,&b);
	c = (*p)(a,b);
	printf("max = %d\n",c);
	return 0;
}
int max(int x,int y)
{
	int z;
	if(x>y)
	{
		z=x;
	}
	else
	{
		z=y;
	 } 
	return(z);
}

How to define and use pointer variables pointing to functions

Type name (* pointer variable name) (function parameter table column)
1. You can only point to functions of the type specified during definition
2. If you want to call a function with a pointer, you must first point to the function with a pointer variable
P = max;//max entry address to p
3. When assigning a value to a function pointer, only the function name is given and no parameters are given
4. When calling a function with a function pointer variable, you only need to write the argument in parentheses after (* p) instead of the function name
5. Arithmetic operations cannot be performed on pointer variables pointing to functions
6. calling function by function name can only call a function, and calling function through pointer variable is more flexible. It can call different functions successively according to different situations.

#include<stdio.h>
int main()
{
	int max(int,int);
	//int (*p)(int,int);
	int min(int x,int y);
	int a=3,b=4,c,zh;
	//p = max;
	scanf("%d",&zh);
	if(zh == 1)
	{
		int (*p)(int,int);
		p = max;
		c = (*p)(a,b);
		printf("max = %d\n",c);
	}
	else if(zh == 2)
	{
		int (*p)(int,int);
		p =min;
		c = (*p)(a,b);
	
printf("max = %d\n",c);
}
//c = (*p)(a,b);
//printf("max = %d\n",c);
return 0;

}
int max(int x,int y)
{
int z;
if(x>y)
{
z=x;
}
else
{
z=y;
}
return(z);
}
int min(int x,int y)
{
int z;
if(x>y) z=y;
else z=x;
return (z);
}

Pointer to function as function parameter

An important use of pointer variables pointing to functions is to pass the function's entry address as a parameter to other functions

There are two numbers a,b input 1 output maximum number input 2 output minimum number input 3 output two numbers and

#include<stdio.h>
int main()
{
	int max(int,int);
	int min(int x,int y);
	int a=3,b=4,c,zh;
	scanf("%d",&zh);
	int and1(int x,int y);
	int fun(int x,int y,int(*p)(int,int));
	if(zh ==1) fun(a,b,max);
	else if(zh == 2) fun(a,b,min);
	else if(zh ==3) fun(a,b,and1);
	
	return 0;
}
int fun(int x,int y,int(*p)(int,int))
{
	int result;
	result = (*p)(x,y);
	printf("%d\n",result);
}
int max(int x,int y)
{
	int z;
	if(x>y)
	{
		z=x;
	}
	else
	{
		z=y;
	 } 
	return(z);
}
int min(int x,int y)
{
	int z;
	if(x>y) z=y;
	else z=x;
	return (z);
}

int and1(int x,int y)
{
	int z;
	z = x+y;
	return z;
}

Definite integral (wrong)

#include<stdio.h>
#include<math.h>
int main()
{
	float integral(float a,float b,float (*fun)(float));
	float f3(float x);
	float a,b,(*p)(float);
	scanf("%d,%d",&a,&b);
	p = f3;
	printf("%f\n",integral(a,b,p));
	return 0;
}

float integral(float a,float b,float (*fun)(float))
{
	int n=20;
	float h,s = 0;
	int i;
	h =(b-a)/n;
	for(i=0;i<20;i++)
	{
		s = fun(b+i*h)*h;
	}
	return s;
}

float f3(float x)
{
	return f3(x);
}

Function that returns pointer value

Prototype: type name * function name (parameter list)

#include<stdio.h>
#include<math.h>
int main()
{
	float score[][4] ={{60,70,80,90},{56,89,67,88},{34,78,90,66}};
	int i,k;
	printf("enter number:");
	scanf("%d",&k);
	printf("scores are:");
	float *search(float (*pointer)[4],int n);
	float *p;
	p = search(score,k);
	for(i=0;i<4;i++)
	{
		printf("%5.2f ", *(p+i)); 
	}
	printf("\n");
	return 0;
}
float *search(float (*pointer)[4],int n)
{
	float *pt;
	pt = *(pointer +n);//The value of pt is & score [k] [0] 
	return(pt);
}


#include<stdio.h>
#include<math.h>
int main()
{
	float score[][4] ={{60,70,80,90},{56,89,67,88},{34,78,90,66}};
	int i,k;
	float *search(float (*pointer)[4]);
	float *p;
	for(i=0;i<3;i++)
	{
		 p=search(score +i);
		 if(p == *(score+i))
		 {
		 	printf("NO.%d score:",i);
		 	for(int j=0;j<4;j++)
		 	{
		 		printf("%5.2f ",*(p+j));
			 }
			 printf("\n");
		 }
	}
	return 0;
}
float *search(float (*pointer)[4])
{
	int i=0;
	float *pt;
	pt =NULL;
	for(;i<4;i++)
	{
		if(*(*pointer + i)<60)
		{
			pt = *pointer;
		}
	}
	return(pt);
}

Pointer array and multiple pointers

The elements of an array are pointer type data, which is called pointer array. Each element in the pointer array stores an address, which is equivalent to a pointer variable.
Int *p[4];// Pointer array
Int (* p) [4]; / / one dimensional array pointer variable
Define the general form of a one-dimensional array:
Type name * array name [array length]

Output several strings in alphabetical order from small to large

#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
	char *name[]={"Follow me","Great Wall","FORTRAN","Computer design"};
	int n = 5;
	void sort(char *name[],int n);
	sort(name,n);
	void print(char *name[],int n);
	print(name,n);
	return 0;
 } 
 void sort(char *name[],int n)
 {
 	char *temp;
 	int i,j,k;
 	for(i=0;i<n-1;i++)
 	{
 		k = i;
 		for(j=i+1;j<n;j++)
 		{ 
 			if(strcmp(name[k],name[j])>0)  k=j;
 			
		 }
		 if(k != i)
		 {
		 	temp = name[i];
		 	name[i] = name[k];
		 	name[k] = temp;
		 }
	 }
 }
 
 void print(char *name[],int n)
 {
 	int i;
 	for(i=0;i<n;i++)
 	{
 		printf("%s\n",name[i]);
	 }
 }

Pointer variable pointing to pointer data

Use pointer variables that point to pointer data

#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
	char *name[]={"Follow me","Basic","Great Wall","FORTRAN","Computer design"};
	int n = 5;
	char **p;
	int i;
	for(i=0;i<5;i++)
	{
		p=name+i;
		printf("%s\n",*p);
	}
	return 0;
}

The value of the output element

#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
	int a[5] = {1,3,5,7,9};
	int *num[5]={&a[0],&a[1],&a[2],&a[3],&a[4]};
	int **p,i;
	p = num;
	for(i=0;i<5;i++)
	{
		printf("%d",**p);
		p++;
	}
	retu

rn 0;
}

The pointer array is used as the formal parameter of the main function
Int main(int argc,char *argv[])
The general form of the command line is
Command name parameter 1 Parameter 2... Parameter n

Dynamically allocate memory and variables pointing to it

1. Use malloc function to open up dynamic storage area
Void *malloc(unsigned int size)
Such as malloc (100);
2. Use calloc function to open up dynamic storage area
Void *malloc(unsigned n,unsigned size)
This space is larger enough to hold an array
For example, p = calloc (50,4);
3. realloc function is used to reallocate dynamic storage area
Void *realloc(void *p,unsigned int size);
If you have obtained the dynamic space through malloc or calloc and want to change the size, you can realloc the dynamic space
Realloc(p,50)
4. Release the dynamic storage area with free
Void free(void *p);

Establish a dynamic array, input the scores of 5 students, and use a function to check whether there is any score less than 60, and output unqualified scores

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int main()
{
	int *p1,i;
	p1=(int *)malloc(5 *sizeof(int));
	for(i=0;i<5;i++)
	{
		scanf("%d",p1+i);
	} 
	 void check(int *p);
	 check(p1);
	 
	 
	return 0;
}
void check(int *p)
{
	int i;
	printf("They are fail:");
	for(i=0;i<5;i++)
	{
		if(p[i]<60) printf("%d",p[i]);
	}
	printf("\n");
}