mal*_*ode -1 c++ function char strcpy
我尝试创建自己的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);
}
Run Code Online (Sandbox Code Playgroud)
Mystrlen在循环之前调用一次,而不是每次迭代(以检查循环条件)。这种方式效率非常低。using namespace std- 请参阅此处为什么“使用命名空间 std;” 被认为是不好的做法?MyStrcpy根本不需要打电话Mystrlen- 见上文。为了学习目的,我保持了它假设的方式。s1在实际生产代码中,必须验证输出 char 数组 ( ) 的长度,否则Mystrcpy可能会导致缓冲区溢出(如果s1分配的 s 数量char小于 内容所需的数量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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
289 次 |
| 最近记录: |