[英]Null terminated array in C++
I want to create NULL terminated array in the constructor. 我想在构造函数中创建以NULL结尾的数组。
class Test
{
char name [30];
char Address[100]
};
Test::Test()
{
memset(name ,0, 30);
memset(Address, 0, 100);
}
Is this the correct way to initialize an array to NULL? 这是将数组初始化为NULL的正确方法吗?
Is there any good alternative to this? 有什么好的替代方法吗?
I'd probably do this: 我可能会这样做:
class Test
{
std::string name;
std::string address;
};
If you're planning on using C-style strings, you need only set the first character to a null terminator. 如果您打算使用C样式的字符串,则只需将第一个字符设置为空终止符。
name[0] = Address[0] = 0;
But, in the long run, you will be better off using std::string
instead. 但是,从长远来看,改用
std::string
会更好。
The proper C++ idiom is to value-initialize your C-strings in your constructor's initialization list: 正确的C ++习惯用法是在构造函数的初始化列表中对C字符串进行值初始化:
class Test
{
char name[30];
char address[100];
public:
Test();
};
Test::Test()
: name(),
address()
{ }
This will have the net effect of all elements of Test::name
and Test::address
being set to '\\0'
. 这将把
Test::name
和Test::address
的所有元素设置为'\\0'
的净效果。
Of course, it would be even better to avoid raw C-strings in the first place, but other answers have already made that point... 当然,最好首先避免使用原始的C字符串,但是其他答案已经指出了这一点。
To store strings, it's sufficient put first char to 0. Ie 要存储字符串,将第一个字符设为0就足够了。
Test::Test()
{
name[0] = Address[0] = 0;
}
If you want (for some specific your purpose) to fill the entire arrays, use sizeof to avoid hardcoding indexes. 如果要(出于某些特定目的)填充整个数组,请使用sizeof避免对索引进行硬编码。
Test::Test()
{
memset(name, 0, sizeof(name));
memset(Address, 0, sizeof(Address));
}
I don't know exactly what you want to do, but I should do: 我不完全知道您想做什么,但我应该这样做:
Test::Test()
{
name[0] = 0;
Address[0] = 0;
}
in this way you can interpret your variable as empty string. 这样,您可以将变量解释为空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.