home *** CD-ROM | disk | FTP | other *** search
- 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
- From: bbobak@undergrad.math.waterloo.edu (Brad Bobak)
- Newsgroups: comp.std.c
- Subject: Is this allowed in C?
- Message-ID: <C17p4n.Dx8@undergrad.math.waterloo.edu>
- Date: 21 Jan 93 16:14:46 GMT
- Organization: University of Waterloo
- Lines: 63
-
-
- I was wondering if the following was valid in C. I can't see why it
- wouldn't be, but I'd thought I'd just make sure..
-
-
- struct astruct {
- int something;
- int something_else;
- } blah;
-
- main()
- {
- char *store;
- store = malloc(sizeof(blah));
-
- memcpy(store, &blah, sizeof(blah));
-
- ...
- /* how about this? */
- {
- int another_int = 5;
- memcpy(&((struct astruct *)store)->something, &another_int,
- sizeof(int));
- }
-
- memcpy(&blah, store, sizeof(blah));
-
- if (blah.something == 5)
- ...
- }
-
- and something else similar:
-
- #define CHAR_MASK ((1 << BITS_IN_CHAR) - 1)
- /* I realize this might fail if sizeof(int) == sizeof(char), if this is
- * possible
- */
-
- main()
- {
- int val;
- char *store;
- int ct;
- store = malloc(sizeof(val));
-
- for (ct=0; ct<sizeof(int); ct++)
- store[ct] = (val >> (ct * BITS_IN_CHAR)) & CHAR_MASK;
-
- ...
-
- for (val=0, ct=0; ct<sizeof(int); ct++)
- val |= store[ct] << (ct * BITS_IN_CHAR);
-
- if (val == 5)
- ...
- }
-
- The reason I'm doing it this way is that I've made a memory allocation
- library. And some systems require special alignment of data. So to
- archive something, I have to copy it to a char array. (I realize this
- may be a little slow). This next question probably has surfaced a few
- times, but is there any way to guarantee the right alignment of
- arbritary data on various architectures?
-