模拟实现strcat函数

    技术2025-12-25  14

    1.描述

    char * strcat ( char * destination, const char * source )strcat函数是在一个destination后面追加source串,返回值为destination的头指针。这个函数缺乏必要安全检查,空指针会崩溃,同时也不支持后重叠。(重叠会覆盖destination中的\0,导致source也没有\0,出现死循环)

    2.代码展示

    #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> char* mystrcat(char* dst, const char *src) //char * strcat ( char * destination, const char * source ) { assert(dst&&src); char * ret = dst; while (*dst) { ++dst; } while (*dst++ = *src++); return ret; } void test2() { char arr1[30] = "to be or not to"; char arr2[] = " be!"; strcat(arr1, arr2); printf("%s\n", arr1); char arr4[30] = "to be or not to"; char arr3[]= " be!"; mystrcat(arr4, arr3); printf("%s\n", arr4); } int main() { test2(); system("pause"); return 0; }

    3.结果展示

    Processed: 0.018, SQL: 9