简体   繁体   中英

how to initialize a const struct with a const pointer value

The code below fails to compile with "initializer element is not constant", or similar on gcc and clang.

Is there any way to make z even more constant? It's already a static constant pointer to constant characters.

Can this be made to work (in a standards compliant way) or is it a violation of the standard?

static const char * const z = "1234";
const struct {
    const char * a;
} b = {z};

My specific use case is closer to

const struct {
    char x[5];
    char y[5];
} n = {"12345","abcde"};
static const char * const z = n.x;
const struct {
    const char * a;
} b = {z};

Actually I'd be happier if I could define an alias, something like this

const char z[5] = n.x;

which is bad syntax, but ....

Here's the closest you can get to the specific use case.

#include <stdio.h>

const struct
{
    char x[6];
    char y[6];
}
    n = { "12345", "abcde" };

static const char * const z = n.x;
const struct
{
    const char * const *a;
}
    b = { &z };

int main( void )
{
    printf( "%s\n", *b.a );
}

The address of a previously-declared static-or-global object is always a compile-time constant. So you can assign &z to a provided that a is a pointer-to-a-pointer.

You could use a macro:

struct P {
  char x[5];
  char y[5];
};

#define X(_n, _z, s1, s2) \
  const struct P _n = {s1, s2}; \
  static const char _z[] = s1;

X(n, z, "12345", "abcde")

const struct 
{
  const char * a;
} b = {z};

The pre-prcoessor would create the following:

const struct P n = {"12345", "abcde"}; 
static const char z[] = "12345";

const struct {
  const char * a;
} b = {z};

This compiles perfectly fine.

const struct {
    char x[5];
    char y[5];
} n = {"12345","abcde"};
#define z   n.x
const struct {
    const char * a;
} b = {z};
#include <stdio.h>
int main(void)
{
    printf("%.5s == %.5s == %.5s\n", b.a, z, n.x);
}

The #define meets all stated requirements:

  • It is C and C++ standard conforming.
  • It is an alias, if you want to call it so.
  • It is as constant as it gets.
  • The data in structure n is not duplicated.
  • sizeof z is 5.
  • It is readable and maintainable and portable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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