简体   繁体   English

使用指针的strcopy函数不起作用

[英]strcopy function using pointers not working

I need to make a function that receives two char pointers and copies the contents of one into the other, and then returns the beginning of the pointer. 我需要制作一个函数,该函数接收两个char指针并将一个指针的内容复制到另一个指针中,然后返回指针的开头。 I have been messing with this for a couple hours now and have read 100 examples that are all different. 我已经弄混了几个小时,并且已经阅读了100个完全不同的示例。 Here is what I have right now: 这是我现在所拥有的:

char * mystrcpy(char * dest, char * src) {
        while(1) {
          if(*src == '\0') {
            *dest = '\0';
            return dest;
          }
          else {
            *dest = *src;
            *src++;
            *dest++;
          }
        }

What you want is to increment the pointers, while you actually increment the character that they point to. 您想要的是增加指针,而实际上增加它们指向的字符。

Change 更改

*src++;
*dest++;

to: 至:

src++;
dest++;
dest++;

dest is a pointer and you are moving it in order to copy values from src So when you return dest it is already pointing to end of the string. dest是一个指针,您正在移动它以便从src复制值。因此,当您返回dest它已经指向字符串的末尾。

So don't move this pointer just copy values to it using indexing. 因此,不要移动该指针,而只是使用索引将值复制到该指针。

int i=0;
while( *src)
{
    dest[i] = *src;
    i++;
    src++;
}

dest[i] = '\0';

return dest;

So even if you fix *dest++ to dest++ what you return will not give the expected results. 因此,即使将*dest++修复为dest++ ,返回的内容也不会得到预期的结果。

these two lines: 这两行:

    *src++;
    *dest++; 

should be: 应该:

    src++;
    dest++;

Notice no de-reference of the pointers as the code needs to increment the pointers, not what the pointers are pointing to. 注意,没有取消对指针的引用,因为代码需要增加指针,而不是指针指向的对象。

And it would be a good idea to save the initial value of dest, so it can be returned. 保存dest的初始值是一个好主意,以便可以将其返回。 And to avoid losing any string already in the dest buffer, I suspect the value (after saving) of dest needs to be incremented by dest += strlen(dest); 为了避免丢失dest缓冲区中已有的任何字符串,我怀疑dest的值(保存后)需要增加dest + = strlen(dest);

so a concentation of the two strings occurs rather than overlaying the initial string in dest. 因此发生了两个字符串的集中,而不是在dest中覆盖初始字符串。

Before that function is called, there should be a check that the dest buffer is long enough to hold the strlen() of both strings +1. 在调用该函数之前,应检查dest缓冲区的长度足以容纳两个字符串+1的strlen()。

+1 is to allow for the termination byte. +1是允许终止字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM