home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.std.c
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: Scalars and Structs
- Message-ID: <1992Jul31.182357.10537@taumet.com>
- Keywords: casts
- Organization: TauMetric Corporation
- References: <1992Jul30.205601.13276@pasteur.Berkeley.EDU>
- Date: Fri, 31 Jul 1992 18:23:57 GMT
- Lines: 30
-
- johnm@cory.Berkeley.EDU (John D. Mitchell) writes:
-
- >Am I correct in taking this to mean that there is no way to cast a
- >structure of known size to a scalar that just so happens to have the same
- >size (or vice versa)?
-
- Correct. You cannot cast to or from a struct type.
-
- Example:
- struct s { char a[4]; } s1;
-
- It seems likely that s1 is the same size as a long, so we might be
- tempted to try to treat its address as the address of a long:
- *(long*)(&s1)
- The problem is that struct s1 might not need to be aligned, whereas
- a long might need alignment. This could result in a runtime abort.
-
- >Is the right thing to do is to use a union? Or is there a better solution.
-
- A union will probably cause the fewest problems. The members will
- start at the same address, and the alignment will be correct.
-
- The best thing to do is to write code which does not require you to
- worry about it at all. Whatever you do risks portability problems.
- In particular, the assumption about the struct and the scalar having
- the same size is unlikely (in general) to be portable.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
- Vice Chair, ANSI C++ Committee, X3J16
-