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

  1. Newsgroups: comp.std.c
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!pacbell.com!decwrl!twwells!bill
  3. From: bill@twwells.com (T. William Wells)
  4. Subject: Re: Aligning an arbitrary pointer?
  5. Organization: None, Mt. Laurel, NJ
  6. References: <14f6u9INNon7@early-bird.think.com> <PDS.92Jul21153918@lemming.webo.dg.com> <14les7INN4m@early-bird.think.com>
  7. Message-ID: <Brwq4F.Iqp@twwells.com>
  8. Date: Fri, 24 Jul 1992 19:00:12 GMT
  9. Lines: 43
  10.  
  11. In article <14les7INN4m@early-bird.think.com> barmar@think.com (Barry Margolin) writes:
  12. : Declare the structure as a union, where one case is an array of page table
  13. : entries, and the other is the preceding stuff.  Then find the array element
  14. : whose address is greater than the address of the end of the preceding
  15. : stuff.  Use the address of that array element as the address of the page
  16. : table.
  17.  
  18. Yes, that works. However, if the object is malloced, you don't
  19. even need the union.
  20.  
  21. There's an awful lot of gobbledygook about this in the standard
  22. but when all is said and done, the standard has eliminated the
  23. notion that all objects are contained in a single address space.
  24. However, each object still behaves as if it were a single address
  25. space in the style to which we had become accustomed, with
  26. increasing and contiguous addresses (in char*s) and the object's
  27. alignment is determined by how it came into being. Malloced
  28. objects are aligned with the strongest restriction possible in the
  29. implementation.
  30.  
  31. Once you have an object, so long as you keep your pointers within
  32. it (or at the end, provided you don't dereference the pointer)
  33. and never generate an pointer with an alignment that is
  34. incompatible with the alignment associated with its type, you can
  35. do all the old pointer manipulation tricks we've all come to know
  36. and love.
  37.  
  38. Suppose that you have a malloced area and a char pointer within
  39. it. You suppose that the pointer points to the start of or to a
  40. byte within some array element and you want to find the start of
  41. the array element. This works:
  42.  
  43.     (array *)((char *)area +
  44.           (pointer - (char *)area)
  45.             / sizeof(array[0])
  46.             * sizeof(array[0]))
  47.  
  48. Watch out for ptrdiff_t oddities, though. (If those are a problem,
  49. one is reduced to a certain amount of searching.)
  50.  
  51. ---
  52. Bill                            { uunet | decwrl | telesci }!twwells!bill
  53. bill@twwells.com
  54.