首页 > 解决方案 > 如何组合两个字符数组而不会出现此错误?

问题描述

我正在学习如何组合两个数组并制作这个简单的代码来理解它。我不断收到错误“必须使用大括号括起来的初始化程序初始化数组”这是什么意思,我该如何解决?谢谢

char a[20] ="hello";

char b[20] = "there";

char c[40] = strcat(a, b);



int main()

{

     printf("%s", c);

}

标签: c++arrayscharacterstrcat

解决方案


字符 c[40] = strcat(a, b);

无效,因为您尝试使用指针分配数组

如果你真的想使用数组:

#include <stdio.h>
#include <string.h>

char a[20] ="hello";

char b[20] = "there";

int main()

{
     char c[40];

     strcpy(c, a);
     strcat(c, b);

     puts(c);
}

要不就

#include <stdio.h>
#include <string.h>

char a[20] ="hello";

char b[20] = "there";

int main()

{
     strcat(a, b);

     puts(a);
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
hellothere
pi@raspberrypi:/tmp $ 

但这是 C 代码,您使用 C++ 标记、strcpystrcat假设接收器有足够的空间,如果这是错误的,则行为未定义。使用std::string来避免这些问题等等


推荐阅读