Dynamically malloc()-able pointers in a struct?
Andrew Koenig
ark at alice.UUCP
Sun Dec 25 00:41:23 AEST 1988
In article <448 at blake.acs.washington.edu>, phaedra at blake.acs.washington.edu (J. Anderson) writes:
> struct xyzzy {
> int plugh;
> long black_rod;
> char *foobar; /* This wants to be a pointer to a variable-length
> * array
> */
> }
Nothing particularly hard about this, except that you must
allocate two separate areas of memory, one for an `xyzzy' object
and one for the character array addressed by `foobar'. The
`xyzzy' object may be a local variable, of course:
struct xyzzy a;
a.foobar = malloc(n);
If you want the `xyzzy' object to be dynamic as well, do this:
struct xyzzy *p;
p = (struct xyzzy *) malloc (sizeof(struct xyzzy));
p->foobar = malloc(n);
To free it, reverse the process:
free(p->foobar);
free(p);
What's the problem?
--
--Andrew Koenig
ark at europa.att.com
More information about the Comp.lang.c
mailing list