看到林锐说在面试时遇到面试官让写一个strcpy的函数,能够从代码风格,思路上面看出一个人的编程水平,所以花了一点时间写了一下代码
一般的C语言初学者容易写出下面这样的代码
// Copy string from array _from[fsi, fei) to array _to[tsi, tei) // return num of copied characters int tran_strcpy(char* from, size_t fs, size_t fe, char*to, size_t ts, size_t te) { // Cannot copy from NULL or copy to NULL if (from == NULL || to == NULL) { return 0; } // Don't need copy any character in such case... // [-1, ...) or [1, 0) ... if (fe - fs < 0 || fs < 0) { return 0; } if (te - ts < 0 || ts < 0) { return 0; } size_t i = 0; for ( ; ts + i < te && fs+i < fe; i++) { to[ts + i] = from[fs + i]; } return i; }