Path: utzoo!mnetor!uunet!lll-winken!lll-tis!ames!oliveb!sun!limes From: limes@sun.uucp (Greg Limes) Newsgroups: comp.lang.c Subject: Re: Help me cast this! Message-ID: <51875@sun.uucp> Date: 4 May 88 00:42:34 GMT References: <294@fedeva.UUCP> Reply-To: limes@sun.UUCP (Greg Limes) Organization: Sun Microsystems, Mountain View Lines: 66 Keywords: pointer to array of struct In article <294@fedeva.UUCP> wrd3156@fedeva.UUCP (Bill Daniels) writes: >How do I cast the malloc() in line 12 of the following program to avoid >the lint cries of "warning: illegal pointer combination" et al? > > >#include > >main() >{ > char *malloc(); > int i; > struct outfile { > int j; > int k; > } (*output)[]; > > output = malloc(sizeof(struct outfile) * 3); > > (*output)[0].j = 1; > (*output)[0].k = 2; > > i = printf("%d %d\n",(*output)[0].j,(*output)[0].k); > > return(i); >} Several quick points: 1) this looks like a job for typedef; if its too complex to figure out the cast, it may be too complex to read the cast. A translation of your code literally into typedefs gives the following results for declaration and cast: typedef struct { int j, k; } outrec; typedef outrec outfile[]; outfile *output; output = (outfile *) malloc (3 * sizeof (outrec)); 2) Pointers to indefinite sized arrays are normally kept simply as a pointer to the beginning of the array. This removes one level of indirection in the code, making it easier to read: all your "(*ptr)[rec].field" constructs change into "ptr[rec].field", giving somewhat easier to write, read, and maintain code. Expanding your program a bit shows one way of using this: /* sortecho: echo parameters, sorted shortest first */ char *malloc (); typedef struct { int len; char *ap; } outrec; int cmp_rec (p, q) outrec *p, *q; { return p->len - q->len; } main (ac, av) char **av; { int nrec; outrec *output; nrec = ac - 1; output = (outrec *) malloc (nrec * sizeof (outrec)); for (i = 0; i < nrec; ++i) { output[i].ptr = av[i + 1]; output[i].len = strlen (av[i + 1]); } qsort (output, nrec, sizeof (outrec), cmp_rec); for (i = 0; i < nrec; ++i) printf ("%6d: %s\n", output[i].len, output[i].ptr); } -- Greg Limes [limes@sun.com] Illigitimi Non Carborundum