#include <iostream>
using namespace std;
void mystrcat(char destination[], const char source[]){
int counter = 0;
while(source[counter] != '/0'){
destination += source[counter];
counter++;
}
destination += '/0';
}
int main(){
}
对于我的代码,当我尝试与函数 mystrcat 连接时,我学校的测试台说存在段错误。我的函数的目的是连接,同时从目标末尾删除 NULL 并将其添加到源末尾。是否因为我没有删除 NULL 而出现段错误?如果是这样,我如何访问数组的最后一个元素?元素的数量是未知的,所以我不知道我是否可以使用 pop_back。谢谢。
编辑:
#include <iostream>
using namespace std;
void mystrcat(char destination[], const char source[]){
int counter = 0;
int counter2 = 0;
while(destination[counter2] != '/0'){
counter2++;
}
while(source[counter] != '/0'){
destination[counter2 - 1] = source[counter];
counter++;
}
destination[counter] = '/0';
}
int main(){
}
是我编辑过的代码,但现在测试台说它花费的时间太长并且崩溃了。
最佳答案
C++ 中的数组有一个有趣的属性,即它们很容易衰减为指针。
destination += source[counter];
不会将 source[counter]
附加到 destination 的末尾。
取而代之的是,destination
已衰减为一个指针,此操作正在对 destination
进行指针算术运算。
相反,您想执行 destination[destinationLocation] = source[counter];
以实际设置 destination
中的字符。
不要忘记在末尾设置 destination[end] = '\0';
以 null 终止 destination
数组。
最后要注意的一件事是 C++ 无法确保您的数组大小合适。如果 destination
的大小不正确,代码将在运行时因段错误而失败。
为了将来引用,您可能需要研究使用 C++ 的 std::vector类(class)。 std::vector 是一个可变大小的类似数组的容器,它会自动跟踪其大小和内存使用情况。在 C++ 中使用纯数组有时很困难且容易出错(如您刚才所见),因此 std::vector 可以使事情变得更容易。
关于c++ - 在 C++ 中与数组串联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152514/