Re: size of pointer variables
- From: rlb@xxxxxxxxxxxxxxxxxxxxxx (Richard Bos)
- Date: Tue, 31 May 2005 09:03:42 GMT
junky_fellow@xxxxxxxxxxx wrote:
> Richard Bos wrote:
> > junky_fellow@xxxxxxxxxxx wrote:
> >
> > > node_t * pstr_node;
> > > bzero(((char *)pstr_node, sizeof (*pstr_node));
> > >
> > > Is this legal ? Can we typecast structure pointer to char pointer ?
> >
> > The code is not legal, for a couple of reasons. First, bzero() is not an
> > ISO C function. Second, you don't initialise pstr_node, so it points
> > nowhere when you pass it to bzero(). Third, you have a parenthesis too
> > many (and two superfluous, but harmless ones. BTW, I disagree with
> > bjrnove on using sizeof (node_t); the way you have it is more solid.).
> >
> Can you please specify why sizeof(*pstr_node) is better as compared
> to sizeof(struct node_t) ? I thought they both are equivalent.
To the compiler, yes, they're equivalent. But consider what happens if
you change pstr_node from a node_t to a newnode_t. If you use
sizeof(node_t), you still pass the size of a node_t, which may be larger
or smaller than the size of a newnode_t. This would mean that bzero()
only zeroes part of the struct, or writes over its end. If you use
sizeof *pstr_node, you always pass in the right size: the size of the
object which pstr_node points at.
> > It is probably superfluous, though, since the most usual implementations
> > of bzero() take a void * as their first argument, and you can pass any
> > object pointer as a parameter declared as void *, without a cast.
>
> That means pointer variable to any type may be typecasted to (char *)
> but *not* the viceversa ?
Similarly to a void *, yes, except that void *s don't need casts. You
can assign any object pointer to a void *; you can also assign a void *
to any object pointer; but the latter only makes sense if the void *
contains the value of another pointer of the type assigned to. That is,
this is correct:
int *ip, i=4;
void *vp;
ip=&i;
vp=ip;
ip=NULL;
...
ip=vp;
and now ip again contains the address of i, as long as vp has not been
tampered with in the mean time. _This_, however, is not correct:
int *ip, i=4;
void *vp;
float *fp;
ip=&i;
vp=ip;
...
fp=vp;
Your compiler will probably not spot it, but you're indirectly assigning
an int pointer to a float pointer, which is not required to work.
Richard
.
- References:
- size of pointer variables
- From: junky_fellow
- Re: size of pointer variables
- From: Malcolm
- Re: size of pointer variables
- From: junky_fellow
- Re: size of pointer variables
- From: Richard Bos
- Re: size of pointer variables
- From: junky_fellow
- size of pointer variables
- Prev by Date: Re: size of pointer variables
- Next by Date: Re: Difference between '0' and 0
- Previous by thread: Re: size of pointer variables
- Next by thread: Re: size of pointer variables
- Index(es):
Relevant Pages
|