malloced structure initilization

Walter Bright bright at Data-IO.COM
Tue Feb 14 05:46:41 AEST 1989


In article <8894 at alice.UUCP< ark at alice.UUCP (Andrew Koenig) writes:
<In article <202 at sabin.UUCP<, bjm at sabin.UUCP (Brendan J. McMahon) writes:
<< How do you initialize memory malloced for a structure without using calloc,
<< and without initilizing each structure element explicitly?
<How about this?
<	static struct foo init_foo;
<	struct foo *fp;
<	fp = (struct foo *) malloc (sizeof (struct foo));
<	*fp = init_foo;
<init_foo is guaranteed to be initialized because it's static.

Yah, and init_foo is guaranteed to be initialized to a 0 bit pattern,
just like if you called calloc instead of malloc. So where have you
gained anything here? I suggest that you declare init_foo something like:
	static struct foo init_foo = { 0,0L,0.0,(char *)0 };
or whatever is appropriate to the struct members.



More information about the Comp.lang.c mailing list