C++ Can";静态常量字符数组“;在C语言中包含变量的成员

C++ Can";静态常量字符数组“;在C语言中包含变量的成员,c++,c,linux,gcc,C++,C,Linux,Gcc,我的代码如下 #include <stdio.h> static const char *a ="this is a"; static const char *b ="this is b"; char *comb_ab[2] = { a, b }; int main() { int i=0; for(i=0; i<sizeof(comb_ab)/sizeof(comb_ab[0]); i++) { printf("%s\

我的代码如下

#include <stdio.h>

static const char *a ="this is a";
static const char *b ="this is b";

char *comb_ab[2] =
{
    a,
    b
};

int main() {

    int i=0;

    for(i=0; i<sizeof(comb_ab)/sizeof(comb_ab[0]); i++) {
        printf("%s\n",comb_ab[i]);
    }
}
test.c:8:2: error: initializer element is not constant
  a,
  ^
test.c:8:2: error: (near initialization for ‘comb_ab[0]’)
test.c:10:1: error: initializer element is not constant
 };
 ^
test.c:10:1: error: (near initialization for ‘comb_ab[1]’)
如何在gcc上的静态const*char数组中包含变量的memeber?
请帮帮我

在C中,静态存储持续时间对象的初始值设定项必须是常量表达式

变量的值永远不是常量表达式,即使它是
常量
限定变量

因此,不能将
a
的值用作
comb_ab
的初始值设定项

< C++初始化器可能有运行时评估。

要修复C版本,可以将
comb_ab
设置为非静态,并在
main
中定义;或者您可以在
main
中包含代码,该代码使用正确的值“初始化”全局
comb_ab



还有一个类型不匹配:您试图使用
const char*
初始化
char*
。但即使你解决了这个问题,前面的问题仍然存在。使用g++时,您应该已经得到了编译器的诊断。

您可能会使用具有静态存储持续时间的对象地址作为常量表达式,但要付出另一个间接级别的代价。这在C中正式称为地址常数(C11,§6.6/9)


您试图用
const char*
初始化
char*
,这是类型不匹配。检查您的g++编译器输出注意
const char*a
是指向
char
常量数组的非常量指针,如果您想要常量指针,则需要
char const*const a
。在
g++.exe(tdm-1)5.1.0
上测试,代码将不会编译,这是预期的,因为
static const char*
意味着“指向具有内部链接和静态持续时间生存期的常量char的指针”,但您正在将其初始化为“非常量char指针数组”。另一个选项是使
a
b
常量char数组
静态const char a[]=“这是a”;静态常量字符b[]=“这是b”;静态常量char*comb_ab[2]={a,b}
#include <stdio.h>

static const char *a = "this is a";
static const char *b = "this is b";

static const char **comb_ab[2] =
{
    &a,
    &b
};

int main()
{
    for (int i = 0; i < sizeof(comb_ab)/sizeof(comb_ab[0]); i++) {
        printf("%s\n", *comb_ab[i]);
    }
}
static const char *comb_ab[] =
{
    "this is a",
    "this is b",
};