c++ - 在 C++ 中与数组串联?

标签 c++ arrays

#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/

相关文章:

c++ - 如何在不多次调用的情况下使用 GetAsyncKeyState?

c - C中初始化char指针数组

arrays - 在类似表格的自定义对象中检索值

c++ - 在内存中为多个文件保存构造的静态数组c++

javascript - Console.log 输出对象数组

删除对象数组时出现 C++ 堆异常

c++ - 在 OpenGL ES 中使用单个 glDrawElement(triangle_strip...) 调用绘制圆角矩形

c++ - 这个模板参数是什么?

c++ - DX12初始化失败VS2019

java - 如何在java中定义对象数组?