String literal inside struct - C

I need to encapsulate a literal string in a struct. The code below will not compile, but hopefully illustrates what I would like to do?

struct my_struct { char* str = "string literal"; }; 
+4
source share
4 answers

You cannot initialize any members in a structure declaration. You must initialize the structure when instantiating the structure.

 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 better make it const char *str , since you cannot modify string literals in any way.

As an alternative

Provide an initialization function

to initialize your structure in 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 initialize it using a 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; 
+15
source

You will need to instantiate the structure and then set the str member. And if you plan on using 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"}; } 
+1
source

I think you want this:

 struct my_struct { char* z; }; // ... struct my_struct s = {"string literal"}; 
+1
source

As mentioned in the answers, the structure declaration and initialization must be separate, and this must be applied sequentially if necessary for all instances of my_struct . C ++ offers the best solution; if you can use C ++ compilation, then this can be automated using the constructor as follows:

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

Then for all instances, my_struct str will point to the literal constant "string literal" when creating the instance. However, note that this is not a const pointer, pointing to the string const.

0
source

Source: https://habr.com/ru/post/1340699/


All Articles