charles@tasis.eecs.utas.edu.au (Charles Lakos) (06/13/90)
I wonder if the C standard says anything about the order of allocation of memory to fields of a struct. In particular, suppose that I have typedef struct { int a; char c; real b; } t1; typedef struct { int a; char c; real b; something-else d; } t2; t2 v2, *p ... p = &v2; /* set p to point to v2 of type t2 */ Can I then access the fields of v2 in the following way: (t1 *) p -> b If this is not standardised, is it common practice? (The question interests me from the point of view of implementing object- oriented languages in C. Classes could be implemented as struct's and pointers to the object could be coerced to the relevant type without problem.) ----- Charles Lakos charles@tasis.eecs.utas.edu.au Electrical Engineering & Computer Science University of Tasmania Tasmania, Australia.
lewine@dg.dg.com (Don Lewine) (06/14/90)
In article <1563@diemen.cc.utas.oz> charles@tasis.eecs.utas.edu.au (Charles Lakos) writes: >I wonder if the C standard says anything about the order of allocation of >memory to fields of a struct. Yes. See section 3.1.2.5 and section 3.5.2.1 which says, "Within a structure object ... members have addresses that increase in the order that they are declared. ... There may be unnamed holes within a structure, but not at its beginning, as necessary to achieve the appropriate alignment." >Can I then access the fields of v2 in the following way: > (t1 *) p -> b Yes. Donald Lewine uunet!dg!lewine -OR- uunet!ptech!don -OR- Don_Lewine@dgc.ceo.dg.com
gwyn@smoke.BRL.MIL (Doug Gwyn) (06/15/90)
In article <1563@diemen.cc.utas.oz> charles@tasis.eecs.utas.edu.au (Charles Lakos) writes: >Can I then access the fields of v2 in the following way: > (t1 *) p -> b No, but ((t1 *)p)->b should work. You can count on a pointer to the first member of a struct being convertible to a pointer to the struct and vice-versa, and from various constraints in the standard it is possible to conclude that "all structure pointers smell the same", meaning that they have the same size and alignment requirements, so it is also possible to interconvert pointers to two different structure types.