home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / std / c / 3390 < prev    next >
Encoding:
Text File  |  1993-01-21  |  1.8 KB  |  73 lines

  1. Path: sparky!uunet!news.gtech.com!noc.near.net!hri.com!spool.mu.edu!uwm.edu!cs.utexas.edu!torn!watserv2.uwaterloo.ca!watmath!undergrad.math.waterloo.edu!bbobak
  2. From: bbobak@undergrad.math.waterloo.edu (Brad Bobak)
  3. Newsgroups: comp.std.c
  4. Subject: Is this allowed in C?
  5. Message-ID: <C17p4n.Dx8@undergrad.math.waterloo.edu>
  6. Date: 21 Jan 93 16:14:46 GMT
  7. Organization: University of Waterloo
  8. Lines: 63
  9.  
  10.  
  11.  I was wondering if the following was valid in C. I can't see why it
  12.   wouldn't be, but I'd thought I'd just make sure..
  13.  
  14.  
  15.  struct astruct {
  16.     int something;
  17.     int something_else;
  18.  } blah;
  19.  
  20.  main()
  21.  {
  22.     char *store;
  23.     store = malloc(sizeof(blah));
  24.  
  25.     memcpy(store, &blah, sizeof(blah));
  26.  
  27.     ...
  28.     /* how about this? */
  29.     {
  30.         int another_int = 5;
  31.         memcpy(&((struct astruct *)store)->something, &another_int,
  32.                sizeof(int));
  33.     }
  34.  
  35.     memcpy(&blah, store, sizeof(blah));
  36.  
  37.     if (blah.something == 5)
  38.     ...
  39.  }
  40.  
  41.  and something else similar:
  42.  
  43. #define CHAR_MASK ((1 << BITS_IN_CHAR) - 1)
  44. /* I realize this might fail if sizeof(int) == sizeof(char), if this is
  45.  * possible
  46.  */
  47.  
  48.  main()
  49.  {
  50.     int val;
  51.     char *store;
  52.     int ct;
  53.     store = malloc(sizeof(val));
  54.  
  55.     for (ct=0; ct<sizeof(int); ct++)
  56.         store[ct] = (val >> (ct * BITS_IN_CHAR)) & CHAR_MASK;
  57.  
  58.     ...
  59.  
  60.     for (val=0, ct=0; ct<sizeof(int); ct++)
  61.         val |= store[ct] << (ct * BITS_IN_CHAR);
  62.  
  63.     if (val == 5)
  64.     ...
  65.  }
  66.  
  67.  The reason I'm doing it this way is that I've made a memory allocation
  68.   library. And some systems require special alignment of data. So to
  69.   archive something, I have to copy it to a char array. (I realize this
  70.   may be a little slow). This next question probably has surfaced a few
  71.   times, but is there any way to guarantee the right alignment of
  72.   arbritary data on various architectures?
  73.