home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / std / c / 2398 < prev    next >
Encoding:
Text File  |  1992-07-30  |  1.4 KB  |  42 lines

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