abyss.7
abyss.7

Reputation: 14462

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

I want to do the following:

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

Obviously, it doesn't work because I haven't specified the size of a new array. What is an appropriate way to achieve my goal without counting symbols in a string literal?

Usage of std::array is also welcome.

Update #1: even if I put the size of array, it won't work either.

Update #2: it's vital to have a non-const access to the array as a simple char* pointer.

Upvotes: 2

Views: 1025

Answers (3)

user541686
user541686

Reputation: 210455

I don't get why you're not using std::string; you can do str.empty() ? NULL : &str[0] to get a non-const pointer, so the constness of str.c_str() is not going to pose a problem.

However, note that this is not null-terminated.

Upvotes: 1

Jason R
Jason R

Reputation: 11696

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

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

You can reduce the boilerplate using a macro:

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

The sizeof is evaluated at compile-time, so there is no runtime scanning of the literal string to find its length. The resulting array is null-terminated, which you probably want anyway.

Upvotes: 4

JHumphrey
JHumphrey

Reputation: 999

Since you requested a dynamic array and not wanting to count the length, that rules out std::array<char,N>. What you're asking for is really just std::string - it's dynamic (if need be), and initializes just fine from a char* without counting the length. Internally, it stores the string in a flat array, so you can use it as such, via the c_str() call.

Upvotes: 2

Related Questions