[comp.lang.c] Assignment of void pointer variable

jmbj@grebyn.com (Jim Bittman) (02/18/90)

I am a newcomer to C programming, but I always thought C was MORE
flexible in the handling of variables and pointers than pascal.
I can make an assignment to an unspecified pointer type in pascal in one
step as follows:
var
   varptr : array[0..9] of pointer;
   myint : integer;
begin
   myint := integer(varptr[5]^);
end.
This works in C, but I'd like to combine the last two lines...
  void *varptr[10];
  int  *intptr;
  int  myint;
  intptr = varptr[5]; 
  myint = *intptr;
Goal:  myint = (int) *varptr[5];  /* doesn't work, it's what I want! */
Post or mail suggestions, Thanks for the help!
Jim Bittman
jmbj@grebyn.com

john@stat.tamu.edu (John S. Price) (02/18/90)

In article <19390@grebyn.com> jmbj@grebyn.com (Jim Bittman) writes:
>This works in C, but I'd like to combine the last two lines...
>  void *varptr[10];
>  int  *intptr;
>  int  myint;
>  intptr = varptr[5]; 
>  myint = *intptr;
>Goal:  myint = (int) *varptr[5];  /* doesn't work, it's what I want! */
>Post or mail suggestions, Thanks for the help!
>Jim Bittman
>jmbj@grebyn.com

Umm... I believe this will work.

myint = *(int *)varptr[5];

The reason:
varptr is declared to be a void pointer, so you have
to tell the compiler what you want it to be "looking"
at when you dereference it.  The (int *) cast tells the
compiler that the next pointer is a pointer to an integer,
and the outer dereference takes the integer at that location.

The reason yours didn't work is this:
myint = (int) *varptr[5];

You have a void pointer, defreference it,
and cast the result to an integer.  This,
I assume, isn't what you wanted.

hope this helps, and I might be totally rambling, for
it is quite early in the morning...


--------------------------------------------------------------------------
John Price                   |   It infuriates me to be wrong
john@stat.tamu.edu           |   when I know I'm right....
--------------------------------------------------------------------------