0

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 better way to do a default struct initialization?

4
  • The code you've posted wouldn't even compile. You might have missed something else then too. Commented Jan 23, 2011 at 22:10
  • Make sure the second const is getting correctly referenced in your other file. If it isn't, you'll end up with (likely) example1 ending up being filled with zeros. Commented Jan 23, 2011 at 22:10
  • Please edit your posting to literally copy the code from your actual source files. As several people have observed, the code you posted can't possibly compile - let alone give the behavior you report. So helping you is impossible, since we would have to guess what your code might look like instead. Commented Jan 23, 2011 at 22:16
  • @martin..sorry for incorrect post - quick sample. Edited. Commented Jan 23, 2011 at 22:22

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Michael..thanks a lot for quick answer.Yes, I missed extern. Its working fine now. Thanks again.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.