Functions passed in structs, as args, and init'd

Christopher R Volpe volpe at kirkwood.crd.ge.com
Fri Mar 1 06:31:36 AEST 1991


In article <1991Feb28.051449.25826 at ux1.cso.uiuc.edu>,
CWIKLA at uimrl7.mrl.uiuc.edu (John/Consultant) writes:
|>
|>
|>	I have the following code pieces throughout a program:
|>
|>typedef struct _Astruct{
|>  int (*myfunc)();
|> .
|> .
|> .
|>} Astruct;
|>
|>int
|>a_function();
|>
|>then I do the following in a routine:
|>
|> .
|> .
|> .
|> Astruct *AS;
|>
|>  AS->myfunc = (int(*)())NULL;
|>
|>
|>then later try to change it:
|>
|>  AS->myfunc = a_function;
|>
|>But this doesn't work -- I get a segment dump...Am I doing this
|>wrong??? (It segmentatoin faults at the last C line above.)

The problem is that you are creating a *pointer* to an Astruct, but
you don't have any storage allocated for the structure. When you
do "AS->" you are dereferencing an undefined pointer variable.
I suggest initializing it with:
  AS = (Astruct *) malloc(sizeof(Astruct));

BTW, I had a disagreement with Doug Gwyn a while back about the use
of that cast. (Yeah, I know, who am I to dispute Doug anyway?) It seems
perfectly fine to me because the very same conversion is permitted
implicitly by assignment without the cast, but Doug says there is nothing
in the Standard that says that a null pointer constant may be cast to
a function pointer. (Is this correct, Doug?)
                                         
==================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com



More information about the Comp.lang.c mailing list