Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!linus!philabs!cmcl2!seismo!columbia!caip!princeton!allegra!ulysses!mhuxr!mhuxn!ihnp4!ltuxa!ttrdc!levy From: levy@ttrdc.UUCP (Daniel R. Levy) Newsgroups: net.lang.c Subject: Declaring pointer to array of structures, within a structure Message-ID: <909@ttrdc.UUCP> Date: Mon, 2-Jun-86 19:18:06 EDT Article-I.D.: ttrdc.909 Posted: Mon Jun 2 19:18:06 1986 Date-Received: Wed, 4-Jun-86 19:11:07 EDT Organization: AT&T, Computer Systems Division, Skokie, IL Lines: 68 Hello out there, ye Gurus. I have a situation: typedef struct foo { char *a; char *b; }; typedef struct bar { char *c; struct foo *d; /* Is this right, to point to an ARRAY of struct foos, please read on */ }; /* Here's what I'd like to do */ main() { char *malloc(); struct bar *BAR; /* allocate space for one bar: */ BAR=(struct bar *)malloc((unsigned)sizeof(struct bar)); /* allocate space for array of ten struct foos and have BAR->d point to that space: */ BAR->d=(struct foo *)malloc((unsigned)(10 * sizeof(struct foo))); /* Use members of this array of struct foo, e.g.: */ (BAR->d)[5].b="This is a test\n"; /* .... */ return 0; /* if I haven't core dumped :-) */ } Now this seems to work perfectly well, and lint says nary a word about this code except for a complaint about the possible alignment problem from the cast of malloc(), which I presume is normal. But what bugs me is that in my typedef of bar, I don't say that member d is a pointer to an ARRAY of struct foo, I just say that it is a pointer to one struct foo. Is this kosher, or have I violated some subtle but important distinction between arrays and pointers to them? Remember, I'd like to be able to treat member d as I would the name of any other array in referencing the memory it points to. When I tried to say d is a pointer to an array of struct foo and tried: struct foo *(d[]); or struct foo (*d)[]; this caused cc to shoot its cookies all over the place later in the code about illegal lhs when trying to store the pointer I got from malloc() in BAR->d. Which makes sense to me, because arrays aren't lvalues. But still I feel like something is Missing. I can't seem to find anything in K&R about how to handle this. Is my code above OK as is with respect to the declaration of d and subsequent use of BAR->d or are there more changes which must be made to make the code fit to be seen by Royalty? Gurus hither and yon are welcome to offer whatever advice by mail or posting that they see fit, and adTHANKSvance. -- ------------------------------- Disclaimer: The views contained herein are | dan levy | yvel nad | my own and are not at all those of my em- | an engihacker @ | ployer or the administrator of any computer | at&t computer systems division | upon which I may hack. | skokie, illinois | -------------------------------- Path: ..!{akgua,homxb,ihnp4,ltuxa,mvuxa, vax135}!ttrdc!levy