【发布时间】:2015-01-27 03:02:42
【问题描述】:
我正在编写一个 C++ 函数,该函数应该通过将每个元素一个字符一个字符地复制到一个新数组中来复制一个字符数组。理想情况下,如果我发表声明
char* a = "test";
char* b = copyString(a);
那么 a 和 b 都应该包含字符串“test”。但是,当我打印复制的数组 b 时,我得到“测试”加上一系列似乎是指针的无意义字符。我不想要那些,但我不知道我哪里出错了。
我目前的功能如下:
char* copyString(char* s)
{
//Find the length of the array.
int n = stringLength(s);
//The stringLength function simply calculates the length of
//the char* array parameter.
//For each character that is not '\0', copy it into a new array.
char* duplicate = new char[n];
for (int j = 0; j < n; j++)
{
duplicate[j] = s[j];
//Optional print statement for debugging.
cout << duplicate[j] << endl;
}
//Return the new array.
return duplicate;
}
为了理解 C++ 的某些方面,我不能使用字符串库,这是我找到的其他答案在这种情况下的不足之处。非常感谢您对此问题的任何帮助。
编辑:虽然我的 stringLength 函数很好 - 也许我错了。
int stringLength(char* s)
{
int n;
//Loop through each character in the array until the '\0' symbol is found. Calculate the length of the array.
for (int i = 0; s[i] != '\0'; i++)
{
n = i + 1;
}
//Optional print statement for debugging.
// cout << "The length of string " << s << " is " << n << " characters." << endl;
return n;
}
【问题讨论】:
-
我怀疑你的
stringLength函数不计算空终止符。 -
明显的“无 0 终结符”案例...
-
也许我应该将它包含在我的问题中。 (编辑:按 Enter 似乎发布评论而不是跳过一行。)
-
int stringLength(const char* s) { int n = 0; for (; *s; s++, n++); return n; }怎么样,保存变量并避免索引运算符。-O3将两个函数优化为大致相同的程序集,因此可能并不重要。
标签: c++ arrays string pointers char