[comp.lang.c] dynamic mem allocation for structures

richw@rosevax.Rosemount.COM (Rich Wagenknecht) (01/07/88)

Assuming I have a structure like:

struct junk {
	type element1;
	type element2;
}
 
(The elements in the structure are not important.)
And I have a pointer:

struct junk *junk_ptr;

How do I type cast my void pointer from malloc? The following doesn't seem
to work.

junk_ptr = (struct junk *)malloc( sizeof(struct junk));

Is the above statement possible? If not, any suggestions?

Thanks for your help,

-- 
Rich W

richw@rosevax.Rosemount.COM
Disclaimer: My views may not represent my own much less my employer's.

gwyn@brl-smoke.ARPA (Doug Gwyn ) (01/09/88)

In article <3834@rosevax.Rosemount.COM> richw@rosevax.Rosemount.COM (Rich Wagenknecht) writes:
>junk_ptr = (struct junk *)malloc( sizeof(struct junk));

That's the right method.  Two comments:
	(a) Make sure you properly declare malloc -- don't let it
	default to int-valued.
	(b) Ignore the "lint" warnings about possible pointer
	alignment problems; "lint" doesn't understand that malloc
	values are always pessimally aligned.