Re: Flexible arrays - v confused
Keith Thompson wrote:[color=blue]
> websnarf@gmail. com writes:[color=green]
> > Chris Torek wrote:[color=darkred]
> >> #include <stdlib.h>
> >> struct vector {
> >> size_t n; /* number of values in the vector */
> >> double val[1]; /* actually size n */
> >> };
> >>
> >> struct vector *vec_new(size_t n) {
> >> struct vector *p;
> >>
> >> /* need n-1 here because the array has an "extra" element */
> >> p = malloc(sizeof *p + (n ? n - 1 : 0) * sizeof p->val[0]);[/color]
> >
> > I do this as follows:
> >
> > p = (struct vector *) malloc (offsetof (struct vector, val) +
> > n * sizeof (p->val[0]));
> >
> > Which means I need a #include <stddef.h>[/color]
>
> Why do you uselessly cast the result of malloc()?[/color]
Because I like to use automatic error detection tools when I program,
and that includes using a C++ compiler (which has stricter type
checking). It means I have to conceed to things like the above in
order to gain the benefit of stronger type checking elsewhere in my
programs.
So if you take the opposite point of view, would it be fair to say that
you avoid things like Lint and ignore warning messages coming from your
compiler? Or are you saying that anything superfluous, like comments
and whitespace, should be eradicated from code?
--
Paul Hsieh
Keith Thompson wrote:[color=blue]
> websnarf@gmail. com writes:[color=green]
> > Chris Torek wrote:[color=darkred]
> >> #include <stdlib.h>
> >> struct vector {
> >> size_t n; /* number of values in the vector */
> >> double val[1]; /* actually size n */
> >> };
> >>
> >> struct vector *vec_new(size_t n) {
> >> struct vector *p;
> >>
> >> /* need n-1 here because the array has an "extra" element */
> >> p = malloc(sizeof *p + (n ? n - 1 : 0) * sizeof p->val[0]);[/color]
> >
> > I do this as follows:
> >
> > p = (struct vector *) malloc (offsetof (struct vector, val) +
> > n * sizeof (p->val[0]));
> >
> > Which means I need a #include <stddef.h>[/color]
>
> Why do you uselessly cast the result of malloc()?[/color]
Because I like to use automatic error detection tools when I program,
and that includes using a C++ compiler (which has stricter type
checking). It means I have to conceed to things like the above in
order to gain the benefit of stronger type checking elsewhere in my
programs.
So if you take the opposite point of view, would it be fair to say that
you avoid things like Lint and ignore warning messages coming from your
compiler? Or are you saying that anything superfluous, like comments
and whitespace, should be eradicated from code?
--
Paul Hsieh
Comment