2

Is it true that the first element always at a lower address than the last element,no matter whether it's in stack or heap?

compile-fan
  • 16,885
  • 22
  • 59
  • 73
  • possible duplicate of [Can a C++ compiler re-order elements in a struct](http://stackoverflow.com/questions/916600/can-a-c-compiler-re-order-elements-in-a-struct) – MByD Apr 30 '11 at 03:11

2 Answers2

1

Yes, you can assume that objects of a given class are all laid out the same way in memory, no matter where they are stored.

Note that the above doesn't imply anything about which end is stored at a lower address. The compiler may choose to reorder the fields of the class as it sees fit.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

Um, yes. The elements of a struct are located in memory in the same order they're defined in the struct definition. They may have padding between them (but there's guaranteed to be no padding before the first one, and a pointer to a struct can be safely cast to a pointer to the first element of that struct), but they always get laid out in memory in the same order.

Can we ask why you're asking?

Chris Lutz
  • 73,191
  • 16
  • 130
  • 183
  • But the book I'm reading says it depends on endianness,so it's not always true the first element is at lower address or not. – compile-fan Apr 30 '11 at 03:53
  • @compile-fan - Endianness should affect the ordering of bytes within an integer, but I don't believe the standard says that that affects the ordering of different variables relative to each other. – Chris Lutz Apr 30 '11 at 04:08
  • It could affect the order of bitfield elements, but they do not have addresses, so strictly speaking they don't have an "order in memory". – R.. GitHub STOP HELPING ICE Apr 30 '11 at 12:42