以类似于初始化字符串文字的方式初始化字符数组 [英] initializing char arrays in a way similar to initializing string literals

查看:31
本文介绍了以类似于初始化字符串文字的方式初始化字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经初始化了一个字符数组:

Suppose I've following initialization of a char array:

char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'};

而且我还对字符串文字进行了以下初始化:

and I also have following initialization of a string literal:

char stringLiteral[]="hello world";

第一个数组和第二个字符串的内容之间的唯一区别是第二个字符串的末尾有一个空字符.

The only difference between contents of first array and second string is that second string's got a null character at its end.

在初始化一个 char 数组时,是否有宏或其他东西允许我们将初始化文本放在两个双引号之间,但数组没有获得额外的空终止字符?

When it's the matter of initializing a char array, is there a macro or something that allows us to put our initializing text between two double quotation marks but where the array doesn't get an extra null terminating character?

对我来说,当不需要终止空字符时,我们应该使用首先提到的初始化语法,并为初始化文本中的每个字符写两个单引号,以及 virgule 标记,这对我来说没有意义单独的字符.

It just doesn't make sense to me that when a terminating null character is not needed, we should use syntax of first mentioned initialization and write two single quotation marks for each character in the initializer text, as well as virgule marks to separate characters.

我应该补充一点,当我想要一个字符数组时,很明显我不想将它与依赖字符串文字的函数一起使用,而且没有使用字符串文字的功能结果,在我的考虑范围内.

I should add that when I want to have a char array, it should also be obvious that I don't want to use it with functions that rely on string literals along with the fact that none of features in which using string literals results, is into my consideration.

感谢您的回答.

推荐答案

我可能已经找到了一种方法来做我想做的事,虽然它不是我想要的,但它可能具有相同的效果.
首先考虑以下两个类:

I might have found a way to do what i want though it isn't directly what I wanted, but it likely has the same effect.
First consider two following classes:

template <size_t size>
class Cont{
 public:
  char charArray[size];
};
template <size_t size>
class ArrayToUse{
 public:
  Cont<size> container;
  inline ArrayToUse(const Cont<size+1> & input):container(reinterpret_cast<const Cont<size> &>(input)){}
};

在继续之前,您可能需要在这里看看常量表达式构造函数和初始化类型.
现在看下面的代码:

Before proceeding, you might want to go here and take a look at constant expression constructors and initialization types.
Now look at following code:

const Cont<12> container={"hello world"};
ArrayToUse<11> temp(container);
char (&charArray)[11]=temp.container.charArray;

最后,初始化文本写在两个双引号之间.

Finally initializer text is written between two double quotations.

这篇关于以类似于初始化字符串文字的方式初始化字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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