Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #29107

Re: A cast question

From Ian Collins <ian-news@hotmail.com>
Newsgroups comp.lang.c
Subject Re: A cast question
Date 2012-12-10 21:00 +1300
Message-ID <ailj5nFq3nrU2@mid.individual.net> (permalink)
References <16311418-f133-4115-bb15-92575637d2c3@googlegroups.com>

Show all headers | View raw


Jack wrote:
> In the following code (taken from a book):
>
> struct Class {
>     size_t size;
>     void * (* ctor) (void * self, va_list * app);
>     void * (* dtor) (void * self);
>     void * (* clone) (const void * self);
>     int (* differ) (const void * self, const void * b);
> };
>
> void * new (const void * _class, ...)
> {
>     const struct Class * class = _class;
>     void * p = calloc(1, class —> size);
>
>     * (const struct Class **) p = class;        //LINE1
>    if (class —> ctor)
>    {  va_list ap;
>       va_start(ap, _class);
>       p = class —> ctor(p, & ap);
>       va_end(ap);
>    }
>    return p;
> }
>
> At LINE1, why cast P to (const struct Class **) first, then deference it?
> Is not LINE1 equal to the following line?
>
>     (const struct Class *) p = class;

No, the above isn't valid syntax (see the earlier "Casts on lvalues" 
thread for the gore).  Even if it were valid, it would change the value 
of p rather than saving the value of class in the memory pointed to by p.

They could have written

   const struct Class** p = calloc( 1, class->size );

   *p = class;

-- 
Ian Collins

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

A cast question Jack <junw2000@gmail.com> - 2012-12-09 23:30 -0800
  Re: A cast question Ian Collins <ian-news@hotmail.com> - 2012-12-10 21:00 +1300
  Re: A cast question Prathamesh Kulkarni <bilbotheelffriend@gmail.com> - 2012-12-10 03:39 -0800
  Re: A cast question Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-12-10 12:47 +0000

csiph-web