【问题标题】:how do i combine two character arrays without this error?如何组合两个字符数组而不会出现此错误?
【发布时间】:2019-05-05 15:35:41
【问题描述】:
我正在学习如何组合两个数组并制作了这个简单的代码来理解它。我不断收到错误“数组必须用大括号括起来的初始化程序初始化”这是什么意思,我该如何解决?
谢谢
char a[20] ="hello";
char b[20] = "there";
char c[40] = strcat(a, b);
int main()
{
printf("%s", c);
}
【问题讨论】:
标签:
c++
arrays
character
strcat
【解决方案1】:
char 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++ 标记,strcpy 和 strcat 假设接收器有足够的空间,如果这是错误的,则行为未定义。使用 std::string 来避免这些问题等等
【解决方案2】:
在 C++ 中,你还不如使用字符串来做到这一点。
#include <string>
#include <iostream>
// ...
std::string a = "hello";
std::string b = "world";
std::string c = a + b;
std::cout << c << std::endl;