Casting diff structures to char*

Will Crowder willcr at bud.sos.ivy.isc.com
Tue May 14 02:41:25 AEST 1991


In article <6214 at mahendo.Jpl.Nasa.Gov>, robert at nereid.jpl.nasa.gov (Robert
Angelino) writes:

|> struct one
|> {
|>  int a,rnum;
|> };
|> struct two
|> {
|>  char b;
|>  int a,rnum;
|> };
|> my_func(rec,...)
|> 	char	*is_this_correct;
|> {
|> is_this_correct->rnum = ...
|> }
|> 
|> my_func((char*) &a,...);
|> my_func((char*) &b,...);

[gets compiler complaints about the is_this_correct->rnum]

|> Am I doing this correctly??

No.

The parameter you're passing to my_func() is a char *, which includes no
information about structure members.  The compiler has no idea what
is_this_correct->rnum means, and there is not enough information in the call
for it to know.

If you only need to access rnum and no other members of the structs within
the function, just declare it as:

my_func(rnump)
int *rnump;
(
     *rnump = ...
}

and call it as

my_func(&a.rnum);
my_func(&b.rnum);

If you need to access other members of structs a and b in the same function,
then you're going to have to include information about which kind of struct
pointer you're passing in the call, and the function itself is going to have
to have knowledge of those types.  Something like:

my_func(sp, type)
char *sp;
int type;
{
     if (type == STRUCTURE_TYPE_A)
          (struct a *)sp->rnum = ...
     else
          (struct b *)sp->rnum = ...
}

Pretty ugly, huh?

Also, if this is ANSI C, you want to use void * rather than char * as the
generic or "opaque" pointer.

Remember, don't pass more information than you need down to the function.

Hope this helps,

Will

--------------------------------------------------------------------------------
Will Crowder, MTS            | "I was gratified to be able to answer quickly,
(willcr at ivy.isc.com)         |  and I did: I said I didn't know."
INTERACTIVE Systems Corp.    |		-- Mark Twain



More information about the Comp.lang.c mailing list