在C 中构造函数中初始化C阵列的错误
error in initializing the c-array in the constructor in c++
这是我的代码,我在初始化构造函数中的char数组时会遇到错误。我还试图用字符串初始化它,但全都徒劳无功。良好的帮助将不胜感激。
#include <iostream>
using namespace std;
class employe
{
char name[30];
int id;
public:
employe(int a, char b[30] ) :id(a), name(b)
{
}
char getid()
{
return name;
}
};
问题是,当数组传递给函数(构造函数只是一个函数)时,它将 decay 到指向其第一个元素的指针。
这意味着构造函数中的参数b
确实是 pointer (键入 char*
),并且您无法初始化指针的数组。
最简单的解决方案是从指针复制到构造函数内部的数组:
// Copy the string from b to name
// Don't copy out of bounds of name, and don't copy more than the string in b contains (plus terminator)
std::copy_n(b, std::min(strlen(b) + 1, sizeof name), name);
a 更好解决方案是将std::string
用于字符串,然后您可以像现在尝试尝试一样初始化。
相关文章:
- 当我的阵列太大时出现分段错误
- 仅在大型阵列上出现合并排序分段错误
- 访问特定阵列位置/索引时出现分段错误
- 为什么删除分配的阵列会导致内存错误?
- 动态 2D 阵列.为什么分段错误?
- 分配给阵列时出现分段错误?黑客排名 2D 阵列 - DS.
- 删除阵列时出现分段错误
- 保护类内存阵列以检测分段错误
- 3D 阵列中的瓦尔格林德错误C++
- OpenMP 环路阵列访问中的错误共享
- C++ Visual 工作室中的逻辑错误.阵列打印的是地址而不是内容
- 排序阵列会使指针链接错误
- 为什么在迭代中迭代时,为什么我不会出现限制阵列错误
- 问题创建和返回锯齿状阵列(错误std :: bad_array_new_length)
- TBB免费图像lambda阵列比较错误
- 打印我的字符串阵列时,会遇到细分错误
- 删除指向排序的字符串阵列的指针会在运行后会有一个错误
- 在C 中构造函数中初始化C阵列的错误
- 当我尝试创建两个后缀阵列时,为什么要获得EXC_BAD_ACCESS错误
- 分段错误 - C++阵列