Implementing a string copy function in C

前端 未结 9 1879
谎友^
谎友^ 2020-12-20 00:57

At a recent job interview, I was asked to implement my own string copy function. I managed to write code that I believe works to an extent. However, when I returned home to

9条回答
  •  盖世英雄少女心
    2020-12-20 01:40

    char * mycpy (char * destination, char * source) {
    
      if (!destination || !source) return NULL;
    
      char * tmp = destination;
    
      while (*destination != NULL || *source != NULL) {
        *destination = *source;
        destination++;
        source++;
      }
    
      return tmp;
    }
    

    In the above copy implementation, your tmp and destination are having the same data. Its better your dont retrun any data, and instead let the destination be your out parameter. Can you rewrite the same.

提交回复
热议问题