I'm not sure how the following code works. I thought you had to do {'h', 'e' ...etc...}
but it seems to work fine. On the other hand if you do std::array<const char*
it only adds one element to the array. Are there special rules for string literal initialization?
std::array<char, strlen("hello world!") + 1> s = {"hello world!"};
for (size_t i = 0; i < s.size(); ++i)
{
std::cout << s[i];
}
Class std::array
is an aggregate. In this statement:
std::array<char, strlen("hello world!") + 1> s = {"hello world!"};
list initialization is used. As the first and only element of this instantiation of the class std::array
is a character array it may be initialized with string literals.
It would be more correctly to use sizeof
operator instead of function strlen
:
std::array<char, sizeof( "hello world!" )> s = {"hello world!"};
Also you could write
std::array<char, sizeof( "hello world!" )> s = { { "hello world!" } };
because the character array in turn is an aggregate.
According to the C++ Standard
8.5.2 Character arrays [dcl.init.string]
1 An array of narrow character type (3.9.1),
char16_t
array,char32_t
array, orwchar_t
array can be initialized by a narrow string literal,char16_t
string literal,char32_t
string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces (2.14.5). Successive characters of the value of the string literal initialize the elements of the array.[ Example:
char msg[] = "Syntax error on line %s\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With