首页 > 解决方案 > 使用 C++ 中的函数在第三个中连接两个 char 数组所需的调试帮助

问题描述

我只是不知道为什么它没有编译。花了一个小时后,我决定向你们寻求帮助。根据我的理解,第一个“for”循环肯定会将整个字符串 s1 复制到 s3。我不知道它为什么会崩溃。实际上我很天真地编程更多地被称为“C++初学者”。所以我不想使用内置函数,因为我正在学习用户定义函数的概念。我将 main() 中的函数称为 string_cat(s1,s2);

 void string_cat(char *s1, char*s2){
    char s3[200]; int i = 0, j = 0;
    for (i=0; s1[i] != '\0'; i++){
        s3[i] = s1[i];
    }
    while (s3[i] != '\0')
    {
        i++;
    }

    while (s2[j] != '\0')
    {
        s3[i++] = s2[j++];

    }
    s3[i] = NULL;

    cout << s3 << endl;

    }

标签: c++

解决方案


我对您的代码进行了微小的更改:

#include<iostream>

using namespace std;


void string_cat(char *s1, char*s2)
{
    char s3[200]; int i = 0, j = 0;
    for (i=0; s1[i] != '\0'; i++){
        s3[i] = s1[i];
    }

    while (s2[j] != '\0')
    {
        s3[i++] = s2[j++];

    }
    s3[i] = '\0';

    cout << s3 << endl;

}

int main()
{
        char str1[5] = "abcd";
        char str2[5] = "efgh";

        string_cat(str1, str2);
}

你应该写: s3[i] = '\0';

编译:

$ g++ StringMerge.cpp -o StringMerge.o

跑:

$ ./StringMerge.o
abcdefgh

推荐阅读