c语言程序设计 字符串拷贝拷贝演变与初衷

/*v1*/
void strcpy(char *s, char *t)
{
  int i;
  
  i = 0;
  while((s[i] = t[i]) != '\0')
    i++;
}

/*v2*/
void strcpy(char *s, char *t)
{
  while((*s = *t) != '\0'){
    s++;
    t++; 
  }
}

/*v3*/
void strcpy(char *s, char *t)
{
  while((*s++ = *t++) != '\0')
    ;
}

/*v4:final verison in <<The C Programming Language>>2nd*/
void strcpy(char *s, char *t)
{
  while(*s++ = *t++)
    ;
}

实际上以上版本还演变到实际面试当中碰到的:
/*v4*/
void strcpy(char *s, const char *t)
{
  while(*s++ = *t++)
    ;
}

/*v5*/
char* strcpy(char *s, const char *t)
{
  char *sCopy = s;
  while(*s++ = *t++)
    ;
  return sCopy;
}

/*v5*/
char* strcpy(char *s, const char *t)
{
  if(s==NULL || t==NULL)
    return NULL;

  char *sCopy = s;
  while(*s++ = *t++)
    ;
  return sCopy;
}

今天总结如下(希望今后补充):
v1:数组加下标,虽然使用了一个局部变量,但是代码易读。
v2:修改为简单的指针版本。
v3:这才是是K&D在书中想强调的。就是++的使用会让代码简洁。
v4:在目前mac下gcc编译器会给出警告


警告信息:
warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
while(*dest++ = *src++)

编译器信息:

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1

Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)

Target: x86_64-apple-darwin14.1.0

Thread model: posix

v5:形参的改变会不会该变以往使用c语言标准库的程序,但是就函数功能而言,这样的改变是正确的。
v6:这里涉及到一个问题,空串检查是不是strcpy份内的事情。

 

posted on 2015-03-28 13:07  dotdog  阅读(192)  评论(0编辑  收藏  举报

导航