面试题

#include<iostream>
#include<STRING>
using namespace std;
int main()
{
   char *src = "hello world";
   char * dest = NULL;
   int len = strlen(src);
   //cout<<len<<endl;
   dest = (char *)malloc(len);
   char *d =dest;
   char * s =src[len];
   while (len--!=0)
   {
    d++ = s--;
    cout<<dest;
   }
   return 0; 
}

 

改正后的

 

#include<iostream>
using namespace std;
int main()
{
   char *src = "hello world";
   char * dest = NULL;
   int len = strlen(src);
   dest = (char *)malloc(len);
   char *d =dest;
   char * s = &(src[len]);//*S此时为 '\0'

   len = len + 1;
   while ( len--!= 0)
    *d++ = *s--;     //这里要循环Len + 1次
   
   len = strlen(src);
   for (int i =0; i<=len - 1; i++)  //将d还原
    d--;
   cout<<"d="<<d<<endl;

   return 0; 
}

输出结果 为  hello world 的反转

 参考 strcopy 的写法,也可以这样写

  while ((*d++ = *s--) != *src)
   NULL; 

 

posted @ 2009-01-20 03:42  谭志宇  阅读(444)  评论(1编辑  收藏  举报