Pointer Problems

Michael Griffith griffith at eecs.cs.pdx.edu
Thu Aug 16 06:21:58 AEST 1990


In article <8aliOrS00WBMI1UVYX at andrew.cmu.edu> gh1r+ at andrew.cmu.edu (Gaurang Hirpara) writes:
>Here's a problem which has been bugging me for a while now:
>Ok. I have a struct, call it idiot, with some elements in it, nothing unusual.
>Now, I have another struct, which contains in it a generic 
>pointer (i.e. Ptr <pointername>). 
>How can I make <pointername> point to idiot, AND be able to access the 
>resulting pointer as a pointer to struct. My main problem is that even
>if I do manage to get them to point to the same place (which is a problem
>all by itself), I can't access the internal members of the struct. 

I beleive that you can typecast the pointer like so:

   ((struct window *)generic_pointer)->width = 100;

or something similar. In other words, you typecast it as belonging to the
appropriate pointer type before you try to reference elements in it. You can
also define generic_pointer to be a union of your other structure types and
then access the appropriate structure type:

   union gen_ptr_type {
      struct window *window_ptr;
      struct screen *screen_ptr;
      .
      .
      .
      struct button *button_ptr;
   };

And then you could reference it like so:

   (generic_pointer.window_ptr)->width = 100;

                                      Michael Griffith
                                      griffith at eecs.ee.pdx.edu
                                      uunet!tektronix!psueea!eecs!griffith



More information about the Comp.lang.c mailing list