Chinaunix首页 | 论坛 | 博客
  • 博客访问: 101908964
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-16 21:46:00

 来源:

=malloc(20);
printf("\n");
printf("original string:\n");
for(i=0;i<5;i++)/*输出指针数组各字符串*/
printf("%s\n",ptr1[i]);
printf("input search string:\n");
temp=malloc(20);
gets(temp);/*输入被插字符串*/
i=binary(ptr1,temp,5)/*;寻找插入位置i*/
printf("i=%d\n",i);
insert(ptr1,temp,5,i);/*在插入位置i处插入字符串*/
printf("outputstrings:\n");
for(i=0;i<6;i++)/*输出指针数组的全部字符串*/
printf("%s\n",ptr1[i]);
return;
}
intbinary(char*ptr[],char*str,intn)
{/*折半插入位置*/
int hig,low,mid;
low=0;
hig=n-1;
if(strcmp(str,ptr[0])<0)return0;
/*若插入字符串比字符串数组的第0个小,则插入位置为0*/
if(strcmp(str,ptr[hig])>0)returnn;
/*若插入字符串比字符串数组的最后一个大,则应插入字符串数组的尾部*/
while(low<=hig)
{
mid=(low+hig)/2;
if(strcmp(str,ptr[mid])<0)
hig=mid-1;
else if(strcmp(str,ptr[mid])>0)
low=mid+1;
else return(mid);/*插入字符串与字符串数组的某个字符串相同*/
}
returnlow;/*插入的位置在字符串数组中间*/
}
void insert(char*ptr[],char*str,intn,inti)
{
int j;
for(j=n;j>i;j--)/*将插入位置之后的字符串后移*/
strcpy(ptr[j],ptr[j-1]);
strcpy(ptr[i],str);将被插字符串按字典顺序插入字符串数组*/
}
在程序中,字符串数组的6个指针均分配存放20字节的有效地址。语句ptr1[5]=malloc(20)保证插入字符串后,也具有安全的存储空间,字符串的长度以串中最长的为基准向系统申请存储空间,以保证在串的移动中有足够的存储空间。
阅读(295) | 评论(0) | 转发(0) |
0

上一篇:指针数组(1)

下一篇:指针的地址分配

给主人留下些什么吧!~~