C struct-to-struct assignment - incorrect values in target structure
I have a c struct in header file:-
typedef struct sample
{
char *member1;
char **member2;
long *member3;
unsigned int member4;
} example;
I have declared a default typedef variable in same header file:-
const example defaultValue;
The definition of defaultValue is in c file:-
const example defaultValue =
{
NULL,
NULL,
NULL,
99
};
Now in a different c file if I do,
example example1 = defaultValue;
all members are assigned NULL as expected - but "unsigned int member4" is assigned value of 0 instead of 99. This is very strange because defaultValue.member4 is 99. Can somebody please explain this unusual behavior? Is there a bet开发者_Python百科ter way to do a default struct initialization?
You'll want your header file to declare defaultValue
like so:
extern const example defaultValue;
so you don't run into problems with more than one definition of the object. Without the extern
specifier you'll have each translation unit (that includes the header) defining an instance of defaultValue
, which leads to undefined behavior.
You want them all referring to the one in the .c file file you describe in the question, which is what the extern
specifier will do for you.
Your example seems to contain several mistakes (struct
is missing its r
, and struct's field definition should be terminated by a semicolon, instead of a comma).
Besides, if your defaultValue
is in another source file you should declare it as extern
in your header.
精彩评论