How to initialize a dynamic array of characters with a string literal in C ++?

I want to do the following:

std::unique_ptr<char[]> buffer = new char[ /* ... */ ] { "/tmp/file-XXXXXX" }; 

Obviously, this does not work, because I did not specify the size of the new array. What is a suitable way to achieve my goal without counting characters in a string literal?

Using std::array also welcome.

Update # 1: even if I placed the size of the array, it will not work either.

Update # 2: it is important to have non-constant access to the array as a simple char* pointer.

+2
source share
3 answers

Here's a solution based on std::array :

 std::array<char, sizeof("/tmp/file-XXXXXX")> arr{ "/tmp/file-XXXXXX" }; 

You can reduce the template with a macro:

 #define DECLARE_LITERAL_ARRAY(name, str) std::array<char, sizeof(str)> name{ str } DECLARE_LITERAL_ARRAY(arr, "/tmp/file-XXXXXX"); 

sizeof is evaluated at compile time, so scanning for a continuous line is not required for its length. The resulting array has zero completion, which you probably want anyway.

+4
source

Since you requested a dynamic array and do not want to count the length, this excludes std::array<char,N> . What you are asking for is actually just std::string - it is dynamic (if necessary), and initializes only a fine from char* without regard to length. Internally, it stores the string in a flat array, so you can use it as such using the c_str() call.

+2
source

I do not understand why you are not using std::string ; can you do str.empty() ? NULL : &str[0] str.empty() ? NULL : &str[0] to get a non-constant pointer, so the constant str.c_str() will not create a problem.

However, note that this is not terminated by zero.

+1
source

Source: https://habr.com/ru/post/1210186/


All Articles