Help me cast this!

Greg Limes limes at sun.uucp
Wed May 4 10:42:34 AEST 1988


In article <294 at fedeva.UUCP> wrd3156 at 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 <stdio.h>
>
>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 at sun.com]			Illigitimi Non Carborundum



More information about the Comp.lang.c mailing list