指针数组

来源:互联网 发布:中国人长相 知乎 编辑:程序博客网 时间:2024/06/04 19:25
  1. //_41_指针数组  
  2. //_41_main.cpp  
  3.   
  4. //实例:在一个已经排好序的字符串数组中,插入一个键盘输入的字符串,  
  5. //使其继续保持有序  
  6. //区分char *point[10]和char (*point)[10]的区别  
  7.   
  8. #include <stdio.h>  
  9. #include <stdlib.h>  
  10. #include <string.h>  
  11.   
  12. int main()  
  13. {  
  14.     //声明子函数  
  15.     int binary(char *ptr[],char *str,int n);//查找函数声明  
  16.     void insert(char *ptr[],char *str,int n,int i);//插入函数声明  
  17.   
  18.     int i;  
  19.     char *ptr1[6];  
  20.     printf("请为字符型指针数组赋初值:\n");  
  21.     for(i=0;i<5;i++)  
  22.     {  
  23.         ptr1[i] = (char *)malloc(20);//为指针分配地址  
  24.         gets(ptr1[i]);//输入字符串  
  25.     }  
  26.     ptr1[5] = (char *)malloc(20);  
  27.     printf("\n");  
  28.     printf("original string:\n");  
  29.     for(i=0;i<5;i++)//输出指针数组各个字符串  
  30.         printf("%s\n",ptr1[i]);  
  31.   
  32.     printf("\ninput search string:\n");  
  33.     char *temp;  
  34.     temp = new char[20];//(char *)malloc(20)  
  35.     gets(temp);//输入被插字符串  
  36.     i = binary(ptr1,temp,5);//寻找插入位置  
  37.     printf("i = %d\n",i);  
  38.     insert(ptr1,temp,5,i);//在插入位置i初插入字符串  
  39.     printf("output strings:\n");  
  40.     for(i=0;i<6;i++)//输出指针数组全部字符串  
  41.         printf("%s\n",ptr1[i]);  
  42.   
  43.     system("pause");  
  44.     return 0;  
  45. }  
  46.   
  47. int binary(char *ptr[],char *str,int n)  
  48. {  
  49.     //折半查找插入位置  
  50.     int high,low,mid;  
  51.     low = 0;  
  52.     high = n-1;  
  53.     //若插入字符串比字符串数组的第0个小,则插入位置为0  
  54.     if(strcmp(str,ptr[0])<0)  
  55.         return 0;  
  56.     //若插入字符串比字符串数组的最后一个大,则应插入字符串数组的尾部  
  57.     if(strcmp(str,ptr[high])>0)  
  58.         return n;  
  59.     while(low <= high)  
  60.     {  
  61.         mid = (low+high)/2;  
  62.         if(strcmp(str,ptr[mid])<0)  
  63.             high = mid - 1;  
  64.         else if(strcmp(str,ptr[mid])>0)  
  65.             low = mid + 1;  
  66.         else  
  67.             return mid;//插入字符串与字符数组的某个字符串相同  
  68.     }  
  69.     return low;//插入位置在字符数组中间  
  70. }  
  71.   
  72. void insert(char *ptr[],char *str,int n,int i)  
  73. {  
  74.     for(int j=n;j>i;j--)  
  75.     {  
  76.         strcpy(ptr[j],ptr[j-1]);//将插入位置后的字符串后移  
  77.     }  
  78.     strcpy(ptr[i],str);//将被插字符串按字典排序插入字符串数组  
  79. }  
0 0
原创粉丝点击