问题背景:判断数字x是否在一个包含N个数字的列表中S。
这里采用三种方法来改变主函数中参数值。分别为:返回值(return)、定义全局变量和指针方法 注意(*ptr_location)++ 一定有括号
方式一:返回参数 return int
1 #include <stdio.h>
2 //void search(int n, int x, const int arr[]);
3 int main(void){
4 int arr[6];
5 int i,j,number;
6 number = 0;
7 int result = 0;
8
9 printf("Please input the 6 number: ");
10 for (i = 0; i < 6;i++){
11 scanf("%d", &arr[i]);
12 }
13
14 number = search(6, 5, arr);
15
16 printf("x = arr[%d] = %d ", number, arr[number]);
17
18 return 0;
19 }
/////////////////////////////////////
///Funcion Name: int search(int n, int x, int arr[])
///Parameter: const int arrp[] search int x
///return: int tempt
//*******************************
////////////////////////////////////
20 int search(int n, int x, int arr[]){
21 int i, j,tempt;
22 for (i = 0; i < n;i++){
23 if (x = arr[i]){
24 tempt = i;
25 }
26 }
27 return tempt;//返回值的方式
28 }
方式二:定义全局变量 location
#include <stdio.h>
#define N 6
int location;//全局变量
void search(int n, const int arr[], int x, int location);
int main(void){
int arr[N];
int i;
printf("Please input the 6 number: ");
for (i = 0; i < N;i++){
scanf("%d", &arr[i]);
}
search(6, arr, 5, location);
printf("x = arr[%d] = %d ", location, arr[location]);
return 0;
}
void search(int n, const int arr[], int x, int _location){
_location = 0;
while ((_location<n) && (arr[_location] != x)){
_location++;
}
if (_location >= n){
_location = 0;
}
location = _location;//全局变量
return ;
}
方式三:指针方式改变主函数中的变量值
void search(int n, const int arr[], int x, int* ptr_location){
while ((*ptr_location<=n) && (arr[*ptr_location] != x)){
(*ptr_location)++;//* 和 ++ 有共同优先级,由右至左开始运算。*ptr_location++ 相当于 *(ptr_location++)
}
if (*ptr_location > n){
*ptr_location = 10;
}
//printf("in x = arr[%d] = %d ", *ptr_location, arr[*ptr_location]);
return ;
}