c++ - 如何组合两个字符数组而不会出现此错误?
问题描述
我正在学习如何组合两个数组并制作这个简单的代码来理解它。我不断收到错误“必须使用大括号括起来的初始化程序初始化数组”这是什么意思,我该如何解决?谢谢
char a[20] ="hello";
char b[20] = "there";
char c[40] = strcat(a, b);
int main()
{
printf("%s", c);
}
解决方案
字符 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来避免这些问题等等
推荐阅读
- c# - 在 C# 中保存应用程序配置的最佳方式
- java - 使用 Neo4j 进行 Spring 身份验证
- javascript - 在 TypeScript 中迭代对象的键和值
- javascript - Webpack 5 Html Webpack Plugin 错误“错误:子编译失败:”
- python - 如何在 for 循环中使用 Django 模板过滤器?
- sql-server - 将 Pandas 数据框插入 SQL Server 执行和执行的时间过长
- unit-testing - UWP 单元测试不会出现在 Rider 中
- javascript - 将加载的模型分配给对象三个 Js 中的值
- javascript - 我无法访问我的 axios 发布请求中的数据
- setuptools - 相当于诗歌中的`python setup.py develop`