Assigning an address to an integer

Christopher T. Jewell chrisj at netcom.UUCP
Sat Jun 2 10:46:18 AEST 1990


In article <486 at tau.megatek.uucp> hollen at megatek.UUCP (Dion Hollenbeck) writes:
>From article <1280003 at hpcc01.HP.COM>, by azarian at hpcc01.HP.COM (Randy Azarian):
>> Can I assign an address of a variable to the value of a standard integer?
>> {
>>   int a,d;
>>   a=&d;
>>   bdos(1,a,1);
>> }
>> This works, but gives me the following warning:
>>   warning C4047: '=' : different levels of indirection
>
>
>You can get rid of the problem by casting it:
>
>   a = (int)&d ;
>
>We do this all the time when passing addresses as "magic cookies".
>We obtain them and do the cast.  They are then stored as ints and
>passed around as ints.  When they finally get to the function
>which needs them, they are cast back to a pointer of the proper
>type.

Well, yeah, that will work on some systems.  On others, such as
ms-dos with large model, you will lose half your bits when you do
the cast, since a pointer is 32 bits and an int is 16.  (Randy's
code, containing a call to something called bdos(), looks like it
could suffer from such problems.)  It's not even defined whether
you will lose the most significant 16 bits, or the least significant,
or even all the odd-numbered bits.  <grin>  In brief, the results
are undefined.

It's much safer to pass your magic cookies around as void pointers
(or char pointers for old compilers).  (Or you could do the whole
thing in Modula-2, and just make them opaque types, but let's not
start another language-religion war.  :-) )
-- 
Chris   (Christopher T. Jewell)   chrisj at netcom.uucp   apple!netcom!chrisj



More information about the Comp.lang.c mailing list