Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8322466
  • 博文数量: 1413
  • 博客积分: 11128
  • 博客等级: 上将
  • 技术积分: 14685
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-13 10:03
个人简介

follow my heart...

文章分类

全部博文(1413)

文章存档

2013年(1)

2012年(5)

2011年(45)

2010年(176)

2009年(148)

2008年(190)

2007年(293)

2006年(555)

分类: C/C++

2009-02-24 21:52:53

前两天看了一个C语言字符串拷贝函数的实现,网上许多朋友讨论不可开交:
  char   *strcp(char   *dest,   const   char   *source)
  {
      while(*dest++=*source++);
      return (dest-1);
  }
基本上第一句是没有问题的,*的优先级低于++,所以就进行了逐个字符的复制。但是对于后一句,也就是返回函数值那句,如果直接返回dest,那么返回的是'\0',如果按照上面的程序,应该是字符串的最后一位,但是我觉得还是有些问题。
可以通过这种方式来解决:
  char   *strcp(char   *dest,   const   char   *source)
  {
        char *addr = dest;
        while(*dest++=*source++);
        return addr;
  }
通过一个临时的指针变量addr来存储地址,然后返回最初的地址。因为在 执行*dest++的时候,会将指针指向最后一位。而通过临时变量来保存的话,就比较方便了。
如果想只通过两个变量来表达的话,可以用这种方式:
  char   *strcp(char   *dest,   const   char   *source)
  {
        while(*dest++=*source++);
        return(dest-strlen(source)-1);
  }
注意,返回那句是将指针移至第一位,求源串长度用了strlen,而不是sizeof。
最后,再看一下一段源码:

#include <iostream>
using namespace std;
  char *strcp(char *dest, const char *source)
  {
        char *addr = dest;
        while(*dest++=*source++);
        //return(dest-strlen(source)-1);

        return addr;

  }

  int main()
  {
          char stra[]= "abc";
          char strtemp[3];
          char *ptemp;
          ptemp = strcp(strtemp,stra);
          cout << "stra: " << stra << endl;
          cout << "strtemp: " << strtemp << endl;
          cout << "ptemp: " << ptemp << endl;

          cout << "&stra: " << &stra << endl;
          cout << "&strtemp: " << &strtemp << endl;
          cout << "&ptemp: " << &ptemp << endl;
          cout << "ptemp[0]: " << ptemp[0] << endl;
          cout << "*ptemp: " << *ptemp << endl;
          cout << "*ptemp++: " << *(++ptemp) << endl;
          cout << "*ptemp++: " << *(++ptemp) << endl;
          return 0;
  }

下面是结果:
stra:   abc
strtemp:   abc
ptemp:   abc
&stra:   0x22ff3c
&strtemp:   0x22ff20
&ptemp:       0x22ff1c
ptemp[0]: a
*ptemp:   a
*ptemp++:   b
*ptemp++:   c
阅读(2148) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-03-30 15:24:33

char *strcp(char *dest, const char *source) { while(*dest++=*source++); return(dest-strlen(source)-1); } 当 while(*dest++=*source++)退出时: strlen(source) ==0 dest -strlen(source) -1是什么?? 结果不对吧。