Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
Q&A
Can I access an array element from a pointer to an object contiguous with but outside the array?
C prohibits accessing an array out of bounds even if measures were taken to ensure that what should lie outside those bounds were known: struct MyStruct { int x[2]; int y, z; }; static...
#1: Initial revision
Can I access an array element from a pointer to an object contiguous with but outside the array?
C prohibits accessing an array out of bounds even if measures were taken to ensure that what should lie outside those bounds were known: ``` struct MyStruct { int x[2]; int y, z; }; static_assert(sizeof(MyStruct) == sizeof(int[4]), "Unexpected Padding"); struct MyStruct s; ``` In the above case `y` is guaranteed to be immediately after the last member of `x` because otherwise the `static_assert` would fail at compile-time. Nevertheless any attempt to access the memory in `s.y` using `s.x[2]` would be undefined behavior. However is the converse true? If accessing outside an array given a pointer to inside the array is undefined behavior, is accessing inside an array given a pointer outside the array legal? For example could I access the memory of `s.x[1]` using `(&s.y)[-1]` since `s.y` is **not** an array?