Pointer practice (3)

Array and pointer
Example (1)
Find the maximum and minimum values ​​from 10 numbers

#include<stdio.h>
int max,min;
void max_minjudge(int arr[10],int n);
int main()
{
    
    
     int arr[10];
	 int i;
	 printf("请对10个数进行初始化\n");
	 for(i=0;i<10;i++)
	 {
    
    
		 scanf("%d",&arr[i]);
	 }
     max_minjudge(arr,10);
	 printf("max=%d,min=%d\n",max,min);

	 return 0;
}
void max_minjudge(int arr[10],int n)
{
    
    
	int *p,*arr_end;
	arr_end=arr+n;
	max=min=*arr;
	for(p=arr+1;p<arr_end;p++)
	{
    
    
		if(*p>max)
			max=*p;
		else if(*p<min)
			min=*p;
	}
}

Code analysis:
int max, min; are global variables.
max=min=*arr; in this section, the value symbol ✳ can be used directly because the array name is the address. Take the first element of the array.

At the same time, defining the first array element as the maximum and minimum value does not conflict, because max and min are two variables, just assign the same value to them and compare them with the remaining elements.

Sharing the wrong point
At first I wrote the subletter like this when coding:

void max_minjudge(int arr[10],int n)
{
    
    
	int *p;
	max=min=*arr;
	for(p=arr+1;p<10;p++)
	{
    
    
		if(*p>max)
			max=*p;
		else if(*p<min)
			min=*p;
	}
}

The results of the operation are as follows:
Insert picture description here
For (p=arr+1;p<arr_end;p++)
p=arr+1 is the array name plus a number to indicate the number of elements from the beginning, when p<arr_end (Note: arr_end=arr+ n) When it is
changed to p<10, the entire loop body cannot be executed, and no judgment can be made, so it stays at the first element.
So the output result is that the maximum and minimum values ​​are both 11.
Because p here is a pointer (that is, an address) and its corresponding value cannot be a value unless *p.

Guess you like

Origin blog.csdn.net/yooppa/article/details/112803121