Topic: Is this pointer expression legal?
Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/04/07 Raw View
In article 95Apr7110325@kapella.efg.zfe.siemens.de, mgrimm@efg.zfe.siemens.de (Mathias Grimmberger) writes:
>
>>#include <iostream.h>
>
>struct A
>{
> int m1;
> char m2[ 10 ];
>};
>
>int
>main( void )
>{
> cout << (A*)0x10 << endl;
> cout << (void*)(((A*)0x10)->m2) << endl;
> return 0;
>}
>
>It prints:
>
>0x10
>0x4
>
>so the member of A starts before the start of A itself :-(
Not at all. The results of your code are undefined, since you are
casting an arbitrary int value to a pointer type and then using the
pointer. There is no telling what will happen with such code.
If you just want to find the location or offset of a struct member,
use the "offsetof" macro in <stddef.h>. That macro exists precisely
because finding such offsets cannot be done portably. The compiler
vendor must provide whatever magic is required to find the offset,
so you don't have to write code with undefined semantics.
Please note, however, that you cannot in general use offsetof on structs
having C++ features, but only on C-style structs. (Those having no access
modifiers, no virtual functions and no virtual base classes, in particular.)
For a general C++ class, use pointer-to-member instead of doing computations
with offsetof.
---
Steve Clamage, stephen.clamage@eng.sun.com
Author: mgrimm@efg.zfe.siemens.de (Mathias Grimmberger)
Date: 1995/04/07 Raw View
Hi,
we have got a problem here with a new compiler. We
upgraded from Sun C++ 3.0.1 to 4.0.1 and can't get some stuff to run
now. The following proggy explains the problem:
-------------------- snip snap --------------------
#include <iostream.h>
struct A
{
int m1;
char m2[ 10 ];
};
int
main( void )
{
cout << (A*)0x10 << endl;
cout << (void*)(((A*)0x10)->m2) << endl;
return 0;
}
-------------------- snip snap --------------------
It prints:
0x10
0x4
so the member of A starts before the start of A itself :-(
If you use the NULL pointer instead of the bogus address 0x10 all runs fine
(unfortunately some older software does it the way above). Now we are not
really secure if this pointer stuff is defined by the (upcoming) standard
or is implementation dependent. At least the old Sun compiler and gcc 2.6.3
yield the results we expect. Hopefully somebody can explain wether it's a
bug or a feature...
M.Grimmberger
--
-------------------------------------------------------------------------------
Mathias Grimmberger <mgrimm@arktur.zfe.siemens.de> at EFG, Dresden, Germany
Fon: (0351) 844 2069 | FAX: (0351) 844 2011
+++++++++++ Don't Panic! +++++++++++