zoukankan      html  css  js  c++  java
  • c语言程序设计 字符串拷贝拷贝演变与初衷

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

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

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

    /*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份内的事情。
  • 相关阅读:
    linux主机安装配置chrony时间同步器
    LINUX正则表达式
    文件系统
    “好文章”链接-爬虫脚本
    优秀博客集
    负载均衡LVS(Linux Virtual Server)
    LNMP
    MySQL备份还原
    iptables--SNAT、DNAT实践
    MySQL 基础命令
  • 原文地址:https://www.cnblogs.com/dotdog/p/4374082.html
Copyright © 2011-2022 走看看