Cast struct * --> double * --> struct * Portable ?

Michael Meissner meissner at osf.org
Sat Oct 13 02:23:23 AEST 1990


In article <588 at dptechno.UUCP> dave at dptechno.uucp (Dave Lee) writes:

| Will the following call be generally portable ?
| 
| struct somestruct THIS_ONE;
| 	f_d( (double *) &THIS_ONE , 1 );
| 
| 
| Restated:  is the following series of casts portable ?
| 
| 	struct * -->  double * --> struct *  
| 
| Does this require that the structure be alligned on a sizeof(double) boundry ?
| Would placing a double as the first member of the structure guarentee such
| allignment ?   I Believe that if the structure were allocated with malloc()
| that the resulting pointer would be worst case alligned and therefore
| will not suffer from allignment problems.  How about static or auto structs ?
| 
| I understand that this is not good programming, but there exists a large number
| of routines in a program that are already coded to expect a double * and I would
| prefer not to have to duplicate all that code just to add this special case.
| 
| I suspect that this is not truely portable, but are there any "likely" problems
| with this?  Is there some kludge I should do to make this work, like placing
| a double as the first member of somestruct ?

No, you must have at least one double member within the structure or
union to assure it gets the appropriate alignment.  For passing
generic pointers, consider void * in ANSI systems with a fallback to
char * on moldy old, uncared for systems.  In fact if you want the
strongest alignment requirement within ANSI, it must have a member
whose type is `long double'.

All this aside, it seems a rather dubious programming practice.  I
would recomend, just declaring the pointer to be struct <name> *, and
just not declare <name> within the function.  This is legal, and even
encouraged.  It also should work on most real-world non-ANSI C
compilers.

--
Michael Meissner	email: meissner at osf.org		phone: 617-621-8861
Open Software Foundation, 11 Cambridge Center, Cambridge, MA, 02142

Do apple growers tell their kids money doesn't grow on bushes?



More information about the Comp.lang.c mailing list