Can "static const char array" include a member of a variable in C
My code is as follows
#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]);
}
}
this code works with the g ++ compiler (C ++). but gcc doesn't work. the conclusion is as follows
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]’)
how to include memeber variable in static const * char array on gcc? please help me!
In C, initializers for objects of static storage duration must be constant expressions.
The value of a variable is never a constant expression, even if it is a const-qualified variable.
Therefore, you cannot use the value aas an initializer for comb_ab.
++ .
C, comb_ab main; main, "" comb_ab .
: const char * char *. , . g++, .
. C (C11, §6.6/9).
#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]);
}
}
, a b . :
static const char *comb_ab[] =
{
"this is a",
"this is b",
};