今天在CSDN上看到一道C语言的字符串复制面试题,题目如下:
要求逆序输出输入的字符串,并且不能用第三方变量,函数的原型是 char* strNCopy(const char* source,char* dest)要求不用库函数,
根据要求我写了这样一段程序:
#include <stdio.h> #include <stdlib.h> char* strNCopy(const char* source,char* dest); int main(int argc, char *argv[]) { char* source="1241654654"; char dest[strlen(source)]; printf("%d\n",strlen(dest)); strNCopy(source,dest); printf("%s\n",dest); system("PAUSE"); return 0; } /*** *逆序复制 */ char* strNCopy(const char* source,char* dest) { if(source!=NULL&&dest!=NULL) { while(*++source) ; while(*dest++=*--source) ; return dest; } return NULL; }
以上代码看似实现了功能,但是还是有一个致命的错误,那就是没有判断dest的长度,没有考虑目标串能否容纳的下源窜.