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份内的事情。
  • 相关阅读:
    死锁
    线程池
    jQuery param()作用与使用方法
    jQuery remove()与jQuery empty()的区别
    jQuery局部动态刷新
    jQuery事件函数位置放置的两种方法
    跨语言通信方案的比较—Thrift、Protobuf和Avro
    Nodejs下如何判断文件夹的存在以及删除文件夹下所有的文件
    如何缓存hbase数据以减少下次取数据的时间
    javascript Date对象的介绍及linux时间戳如何在javascript中转化成标准时间格式
  • 原文地址:https://www.cnblogs.com/dotdog/p/4374082.html
Copyright © 2011-2022 走看看