如何初始化字符与字符串在C ++中文字动态数组? [英] How to initialize the dynamic array of chars with a string literal in C++?

查看:279
本文介绍了如何初始化字符与字符串在C ++中文字动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点:

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?

的std ::阵列的使用也是欢迎的。

更新#1:就算我把数组的大小,它也不工作。

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

更新#2:这是有一个的非const重要的访问阵列作为一个简单的的char * 指针。

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

推荐答案

下面是根据的std ::阵列解决方案:

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");

的sizeof 在编译时计算,所以文字字符串的任何运行时扫描发现其长度。结果数组是空终止,你可能想反正。

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.

这篇关于如何初始化字符与字符串在C ++中文字动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆