开发者

String literal inside struct - C

I need to encapsulate a literal string in a struct. The code below won't compile, but hopefully illustrates what I 开发者_运维技巧would like to do?

struct my_struct
{
char* str = "string literal";
};


You can't initialize any members in a struct declaration. You have to initialize the struct when you create an instance of the struct.

struct my_struct
{
   char* str;
};

int main(int argc,char *argv[]) 
{
  struct my_struct foo = {"string literal"};
  ...
}

Since you want the str member to refer to a string literal, you'd better make it a const char *str , as you can't modify string literals any way.

Alternatively

Provide an initialization function

to initialize your struct to a known state every time.

struct my_struct
{
   const char* str;
   int bar;
};

void init_my_struct(strut my_struct *s)
{
   s->str = "string literal";
   s->bar = 0;
}
int main(int argc,char *argv[]) 
{
  struct my_struct foo;
  init_my_struct(&foo);

Or initializing it using the preprocessor:

struct my_struct
{
   const char* str;
   int bar;
}; 

#define MY_STRUCT_INITIALIZER {"string literal",0}
int main(int argc,char *argv[]) 
 {
   struct my_struct foo = MY_STRUCT_INITALIZER;

Or copy from a known object:

struct my_struct
{
   const char* str;
   int bar;
};
const struct my_struct my_struct_init = {"string_literal",0};

int main(int argc,char *argv[]) 
{
   struct my_struct foo = my_struct_init;


You'll have to create an instance of the struct, and then set the str member. And if you plan to use string literals with it, you really should change it to const char* str.

struct my_struct
{
    const char* str;
};

int main() {
    struct my_struct s1;
    s1.str = "string literal";

    /* or */
    struct my_struct s2 = {"string literal"};
}


I think you want this:

struct my_struct
{
    char* z;
};

// ...

struct my_struct s = {"string literal"};


As the answers already given suggest, structure declaration and initialisation must be separate, and this must be applied consistently if it is required for all instances of my_struct. C++ offers a better solution; if you could use C++ compilation, then this can be automated using a constructor as follows:

struct my_struct
{
    my_struct() : str("string literal"){}
    char* str ;
};

Then for all instances of my_struct, str will point to the literal constant "string literal" on instantiation. Beware however that this is a non const pointer pointing to a const string.


Direct initialization is not allowed. Instead what can be done is to make it a pointer and point it to your desirable string.


Another way, but still, you have to use default initialized instance to init your new instances.

struct my_struct
{
    const char * str;
} ms_def {
    .str = "value"
};

int main()
{
    my_struct obj = ms_def;
    printf("%s\n", obj.str);
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜