在C中实现strcpy时出现问题

Ale*_*lex 2 c string strcpy

对于家庭作业,我应该实现string.h库的所有22个函数(2fun2handle).我已经失去了很多功能,但在尝试实现strcpy时遇到了一些麻烦.

经过相当多的修改,这是我对该功能的尝试:

char *new_strcpy(char *dest, const char *src){
    char *copy = (char *) src;
    for(; *copy != '\0'; ++copy, ++dest)
        *dest = *copy;
    return dest;
}
Run Code Online (Sandbox Code Playgroud)

我认为这样可以正常工作.但是,在通过这样一个简单的示例测试我的代码时:

char src[50], dest[50];
new_strcpy(src,  "src");
new_strcpy(dest,  "dest");
printf("dest: %s\n", dest);
printf("src: %s\n", src);
Run Code Online (Sandbox Code Playgroud)

我的输出最终看起来像这样:

dest: dest$
src: src$$$$
Run Code Online (Sandbox Code Playgroud)

当它应该看起来像这样:

dest: dest
src: src
Run Code Online (Sandbox Code Playgroud)

在实现这个函数之前,我已经使用指针将src字符串复制到dest字符串而没有问题..所以我不确定为什么现在这样做.有什么明显的东西我做错了吗?还要注意我已经尝试使用while循环并循环直到*copy为空,并且我已经尝试直接循环遍历传入的原始*dest和*src参数.

Bli*_*ndy 5

您永远不会使用特殊的零字符将实际字符串标记为已完成:

char *new_strcpy(char *dest, const char *src){
    char *copy = (char *) src;
    for(; *copy != '\0'; ++copy, ++dest)
        *dest = *copy;
    *dest=0;
    return dest;
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要copy变量,它只是编译器将为您删除的垃圾.

编辑:根据要求,strcpy不丢弃const且不太详细的经典函数如下:

char *new_strcpy(char *dest, const char *src)
{
  char *ret = dest;            // needed to return, useless as this is
  while(*dest++ = *src++);     // straight byte copy, very unoptimized
  //*dest=0;                   // no longer needed since the copy happens before the check now
  return ret;                  // and return the original buffer (note that you were returning the end)
}
Run Code Online (Sandbox Code Playgroud)