开发者

About the address layout of struct in c/c++

开发者 https://www.devze.com 2023-03-02 07:51 出处:网络
Is it true that the first element always at a lower address than the last e开发者_开发百科lement,no matter whether it\'s in stack or heap?Um, yes. The elements of a struct are located in memory in the

Is it true that the first element always at a lower address than the last e开发者_开发百科lement,no matter whether it's in stack or heap?


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消