part 1
数组名作实参只用写数组名,不加[ ],作形参时则要写明类型、数组名和[ ]。指针变量作形参时要写类型、*和指针变量的名字,作实参时只用写指针变量的名字。
ex1_1源程序:
1 // 练习:使用二分查找,在一组有序元素中查找数据项 2 // 形参是数组,实参是数组名 3 #include <stdio.h> 4 const int N=5; 5 int binarySearch(int x[], int n, int item); 6 int main() { 7 int a[N]={11,32,93,164,215}; 8 int i,index, key; 9 10 printf("数组a中的数据:\n"); 11 for(i=0;i<N;i++) 12 printf("%d ",a[i]); 13 printf("\n"); 14 15 printf("输入待查找的数据项: "); 16 scanf("%d", &key); 17 18 // 调用函数binarySearch()在数组a中查找指定数据项item,并返回查找结果给index 19 // 补足代码① 20 21 index=binarySearch(a,N,key); 22 23 if(index>=0) 24 printf("%d在数组中,下标为%d\n", key, index); 25 else 26 printf("%d不在数组中\n", key); 27 28 return 0; 29 } 30 31 32 //函数功能描述: 33 //使用二分查找算法在数组x中查找特定值item,数组x大小为n 34 // 如果找到,返回其下标 35 // 如果没找到,返回-1 36 int binarySearch(int x[], int n, int item) { 37 int low, high, mid; 38 39 low = 0; 40 high = n-1; 41 42 while(low <= high) { 43 mid = (low+high)/2; 44 45 if (item == x[mid]) 46 return mid; 47 else if(item < x[mid]) /*补足代码②*/ 48 high = mid - 1; 49 else 50 low = mid + 1; 51 } 52 53 return -1; 54 }
运行结果:
ex1_2源程序:
1 // 练习:使用二分查找,在一组有序元素中查找数据项 2 // 形参是指针变量,实参是数组名 3 #include <stdio.h> 4 const int N=5; 5 int binarySearch(int *x, int n, int item); 6 int main() { 7 int a[N]={19,38,97,166,215}; 8 int i,index, key; 9 10 printf("数组a中的数据:\n"); 11 for(i=0;i<N;i++) 12 printf("%d ",a[i]); 13 printf("\n"); 14 15 printf("输入待查找的数据项: "); 16 scanf("%d", &key); 17 18 // 调用函数binarySearch()在数组a中查找指定数据项item,并返回查找结果 19 // 补足代码① 20 21 index=binarySearch(a,N,key); 22 23 if(index>=0) 24 printf("%d在数组中,下标为%d\n", key, index); 25 else 26 printf("%d不在数组中\n", key); 27 28 return 0; 29 } 30 31 //函数功能描述: 32 //使用二分查找算法在x指向的数据项开始的n个数据中,查找item 33 // 如果找到,返回其位置 34 // 如果没找到,返回-1 35 int binarySearch(int *x, int n, int item) { 36 int low, high, mid; 37 38 low = 0; 39 high = n-1; 40 41 while(low <= high) { 42 mid = (low+high)/2; 43 44 if (item == *(x+mid)) 45 return mid; 46 else if(item<*(x+mid)) /*补足代码②*/ 47 high = mid - 1; 48 else 49 low = mid + 1; 50 }
运行结果:
part 2
第一次写的时候用了=给数组赋值,实际上数组之间的赋值要用strcpy函数。
ex2_2源程序:
1 // 练习:使用选择法对字符串按字典序排序 2 #include <stdio.h> 3 #include <string.h> 4 void selectSort(char str[][20], int n ); // 函数声明,形参str是二维数组名 5 int main() { 6 char name[][20] = {"Joe", "Red", "Joseph", "Andy", "Rachel"}; 7 int i; 8 9 printf("输出初始名单:\n"); 10 for(i=0; i<5; i++) 11 printf("%s\n", name[i]); 12 13 selectSort(name, 5); // 调用选择法对name数组中的字符串排序 14 15 printf("按字典序输出名单:\n"); 16 for(i=0; i<5; i++) 17 printf("%s\n", name[i]); 18 19 return 0; 20 } 21 22 // 函数定义 23 // 函数功能描述:使用选择法对二维数组str中的n个字符串按字典序排序 24 void selectSort(char str[][20], int n) { 25 int i,j,k;char temp[10]; 26 for(i=0; i<n-1; i++){ 27 k=i; 28 for(j = i+1 ;j < n; j++){ 29 if (strcmp(str[i], str[j]) >0) 30 { k=j; 31 if (k != i) { 32 strcpy (temp, str[k]); 33 strcpy (str[k], str[i]); 34 strcpy (str[i], temp); 35 } 36 } 37 } 38 } 39 }
运行结果:
part 3
使用指针变量对字符串进行处理的注意事项:
字符指针变量中存放的是字符串的首地址,实参中的字符指针是地址变量,这个值是可以改变的,且在使用前必须指向确定的地址。