[comp.lang.c] Question about using void *

imp@Solbourne.COM (Warner Losh) (01/19/91)

Given something like the following:

struct foo {
	void *bar;
};

struct foo fred[] = {
	{ (void *) 1},
	{ (void *) 3}
};

struct foo george[] = {
	{ (void *) "Warner"},
	{ (void *) "Losh"}
};

In the program where I see this being done, there is a tag that tells
what type each element of the struct foo is, plus some other
information.  What I've presented here are just the basics.

My question is: Is this portable?  Can I stuff an integer into a
pointer and expect to get it back out again?  I know that there are
problems with going the other way (stuff a pointer into an int and
then try to get it back out).

I couldn't find anything in my K&R II to tell me how kosher this
method is.

Warner
-- 
Warner Losh		imp@Solbourne.COM
We sing about Beauty and we sing about Truth at $10,000 a show.

gwyn@smoke.brl.mil (Doug Gwyn) (01/20/91)

In article <1991Jan18.225308.25139@Solbourne.COM> imp@Solbourne.COM (Warner Losh) writes:
>My question is: Is this portable?  Can I stuff an integer into a
>pointer and expect to get it back out again?

Any use of void* is not going to work on some pre-ANSI compilers.

It is not generally safe to try to convert an arbitary integral
value to a pointer.  While the implementation much provide SOME
integral type capable of holding a (properly converted) object
pointer, the converse is not required.  (Only for values
obtained by starting with a valid pointer.)

This is an ideal place to use a union type.