How does the std :: array initializer for char work?

I am not sure how the following code works. I thought you need to do {'h', 'e' ...etc...} , but it seems to work fine. On the other hand, if you execute std::array<const char* , it only adds one element to the array. Are there special rules for initializing string literals?

 std::array<char, strlen("hello world!") + 1> s = {"hello world!"}; for (size_t i = 0; i < s.size(); ++i) { std::cout << s[i]; } 
+7
c ++ c ++ 11 stdarray
source share
2 answers

The std::array is a collection. In this statement:

 std::array<char, strlen("hello world!") + 1> s = {"hello world!"}; 
List initialization is used.

. Since the first and only element of this instance of the std::array class is an array of characters, it can be initialized with string literals.

It would be more correct to use the sizeof operator instead of the strlen function:

 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 is in turn an aggregate.

In accordance with the C ++ standard

8.5.2 Character Arrays [dcl.init.string]

1 Array of narrow character type (3.9.1), char16_t array, char32_t array or wchar_t array can be initialized with a narrow string literal, char16_t string literal, char32_t string literal or wide literal string, respectively, or a correspondingly printed string literal enclosed in curly brackets (2.14.5). Consecutive characters of value string literal initializes the elements of the array.

[Example: char msg [] = "Syntax error in line% s \ n";

+4
source share

Here's a way to achieve this.

 // GOAL std::array<char, sizeof("Hello")> myarray = {"Hello"}; 

i.e. initializing std :: array with a string literal (yes, he used a macro)

 // SOLUTION #define STD_CHAR_ARRAY_INIT(arrayname, string_literal) /*std::array*/<char, sizeof(string_literal)> arrayname = {string_literal} std::array STD_CHAR_ARRAY_INIT(myarray, "Hello"); 

Here are some test codes:

 #include <iostream> #include <array> using std::cout; using std::ostream; template<typename T, size_t N> std::ostream& std::operator<<(std::ostream& os, array<T, N> arr) { { size_t cnt = 0; char strchar[2] = "x"; for (const T& c : arr) { strchar[0] = c; os << "arr[" << cnt << "] = '" << (c == '\0' ? "\\0" : strchar /*string(1, c)*/ ) << "'\n" << '.' << c << '.' << '\n'; ++cnt; } } return os; } #define STD_CHAR_ARRAY_INIT(arrayname, string_literal) /*std::array*/<char, sizeof(string_literal)> arrayname = {string_literal} int main() { std::array STD_CHAR_ARRAY_INIT(myarray, "Hello"); cout << myarray << '\n'; return 0; } 
0
source share

All Articles