【问题标题】:I made my own strcpy function, but it is not working. How to fix it?我制作了自己的 strcpy 函数,但它不起作用。如何解决?
【发布时间】:2022-07-13 16:14:27
【问题描述】:

我尝试创建自己的mystrcpy() 函数,它采用与标准函数相同的参数。它没有响应。数组不会被复制。

size_t Mystrlen(const char* s)
{
    int i = 0;
    while (s[i] != '\0')
    {
        i++;
    }
    return i;
}

char* Mystrcpy(char* s1, const char* s2)
{
    for (int i = 0; i < Mystrlen(s2); i++)
        s1[i] = s2[i];
    return s1;
}

int main()
{
    char s1[50];
    char s2[50];
    cout << "enter the value of second string\n";
    cin >> s2;
    Mystrcpy(s1, s2);
}

https://godbolt.org/z/zWxqxn3Kx

【问题讨论】:

  • 我们需要查看一个名为Mystrlen 的函数来讨论或调试这段代码的作用。代码应该是minimal reproducible example
  • 给您带来的不便,我深表歉意。我已经添加了功能。
  • 现在,定义“不工作”您在发布的代码中调用此函数,但对结果 s1 执行 nothing
  • “数组没有被复制” 我向你保证,在这里显示的代码中,数组确实被复制了。最多但不包括空终止符。您的问题中添加了一个链接,其中显示了复制的字符。
  • Mystrcpy 不需要调用Mystrlen。只需复制字符,直到您击中 nul 终止符。并且不要忘记复制终结者!执行此操作的典型黑客头代码是while (*s1++ = *s2++) ;。如果这对您没有意义,请不要担心。

标签: c++ function char strcpy


【解决方案1】:
  1. 最好在循环之前调用一次Mystrlen,而不是每次迭代(检查循环条件)。这种方式效率很低。
  2. 您没有将零终止符复制到目标字符串。
  3. 与您的错误无关,但无论如何最好避免using namespace std - 请参阅此处Why is "using namespace std;" considered bad practice?
  4. 正如@Pete Becker 所说,MyStrcpy 根本不需要调用Mystrlen - 见上文。为了学习目的,我保留了它的假设方式。
  5. 在实际生产代码中,必须验证输出字符数组(s1)的长度,否则Mystrcpy 会导致缓冲区溢出(如果s1 分配的chars 数量少于所需的chars s2的内容)。

固定代码(直到上面的注释):

#include <iostream>

// size_t Mystrlen(const char* s) ...   // Same as in your code

char* Mystrcpy(char* s1, const char* s2)
{
    size_t len = Mystrlen(s2);  // Call once before the loop
    for (int i = 0; i < len; i++)
    {
        s1[i] = s2[i];
    }
    s1[len] = '\0';     // Add zero termination
    return s1;
}

int main()
{
    char s1[50];
    char s2[50];
    std::cout << "enter the value of second string\n";
    std::cin >> s2;
    Mystrcpy(s1, s2);
    std::cout << "copied string: " << s1 << std::endl;
}

【讨论】:

  • @malscode 如果有用,您可以考虑接受我的回答(点击分数下方的“✔”)。您也可以考虑投票(stackoverflow.com/help/why-vote)。
猜你喜欢
  • 2022-01-10
  • 2023-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多