简体   繁体   English

使用C中的两个字符串初始化const char * const *

[英]Initialise a const char * const * with two strings in C

Does anyone know the correct way of initializing a const char * const * with two literal strings ( "abcdefg" and "hijklmnop" )? 有没有人知道用两个文字字符串( "abcdefg""hijklmnop" )初始化const char * const *的正确方法? I read it was difficult/not possible to convert from a char ** , but I may be wrong. 我读到很难/不可能从char **转换,但我可能错了。

Any help much appreciated. 任何帮助非常感谢。

Instead of pointers-to-pointers, use an array of pointers and initialize them like this: 而不是指针指针,使用指针数组并像这样初始化它们:

const char * const strs[] = {"abcdefg", "hijklmnop"};

So instead of a constant pointer to string constants you now have a constant array to string constants. 因此,不是指向字符串常量的常量指针,而是现在有一个常量数组来表示字符串常量。 C does not allow initializing pointers with braces (unless there is only a single value in them), but it does allow for arrays to be initialized this way. C不允许使用大括号初始化指针(除非它们中只有一个值),但它允许以这种方式初始化数组。

In C99 and up, you can use a compound literal to create an array and use that as an initializer for your pointer. 在C99及更高版本中,您可以使用复合文字来创建数组,并将其用作指针的初始化程序。

const char * const *p = (const char *[]){"abcdefg", "hijklmnop"};

This is equivalent to using a named array like in Kninnug's answer, plus a pointer with an initializer pointing to the array by name: 这相当于使用Kninnug的答案中的命名数组,以及一个带有初始化器的指针,该初始化器按名称指向数组:

const char * const strs[] = {"abcdefg", "hijklmnop"};
const char * const *p = strs;

Except for the fact that the array has a name ( strs ) in one and is anonymous in the other. 除了数组中的名称( strs )在一个中并且在另一个中是匿名的这一事实。

And also let me add that none of these solutions involves converting a char ** to a const char * const * . 并且还让我补充一点,这些解决方案都不涉及将char **转换为const char * const * The way they are constructed, each char * is converted to a const char * individually by virtue of being used as an initializer for an array element that is individually a const char * . 它们的构造方式,每个char *被单独转换为const char * ,因为它被用作一个数组元素的初始化器,它是一个const char * There aren't any char ** 's in the code. 代码中没有任何char **

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM