This is the mail archive of the
guile@cygnus.com
mailing list for the Guile project.
Re: Casting a pointer to a structure
- To: Jost Boekemeier <jostobfe@calvados.zrz.TU-Berlin.DE>
- Subject: Re: Casting a pointer to a structure
- From: Jim Blandy <jimb@red-bean.com>
- Date: 19 Jul 1999 14:18:56 -0500
- Cc: guile@cygnus.com
- References: <199907180151.UAA04587@savonarola.red-bean.com> <p2td7xoearn.fsf@grapefruit.zrz.tu-berlin.de>
> does anyone know if it is possible to cast a pointer to
> a structure into a pointer to the first element of a substructure?
>
> For example:
>
> struct env_funcs {
> int something;
> }
> struct x {
> struct *env_funcs;
> int something;
> }
> struct m {
> struct x x;
> int something;
> }
>
> Now is it possible to cast a pointer to m into a pointer to a pointer
> to struct env_funcs? I know that it is possible to cast a pointer
> to the first element of a structure into a pointer to the whole structure
> but the above construct surprised me.
You may be looking for someone's opinion other than mine, but
anyway... :)
The C *compiler* will let you cast anything to anything you like. So
it's a question of what is guaranteed to be safe.
I assume you actually meant to write:
struct env_funcs {
int something;
}
struct x {
struct env_funcs *env_funcs;
int something;
}
struct m {
struct x x;
int something;
}
ANSI C guarantees that it is safe to cast a pointer to a structure to
a pointer to the type of that structure's first element. Thus, it is
safe to cast a `struct m *' to a `struct x *'. Applying the same rule
again, it is safe to cast a `struct x *' to a `struct env_funcs **'.
I conclude (perhaps erroneously) that you might as well cast a `struct
m *' directly to a `struct env_funcs **', since none of the casts are
actually doing any computation, and the compiler doesn't try to verify
the safety of any of the casts anyway.
I don't have a copy of the standard any more, so I can't say whether
collapsing the two casts into one is kosher.