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;
source share