0

Can I be sure that the following code will work on all platforms?

struct example{
  int a;
  int b;
} example;

*((int*)(((void*)&example) + sizeof(int))) = 33;

This should change the value of (b) inside (example) to 33.

Daniel
  • 1
  • 1
  • No, because padding might exist, not to mention this violates aliasing rules. Why do you think you want to do this? Also, how would this even compile? `33` cannot be assigned to a `struct example`, which is what your pointer points to - albeit, by the time you've added `sizeof(int) * sizeof(example)` bytes to it as you do here, not a valid/dereferenceable one. – underscore_d Jan 08 '20 at 15:11
  • padding does not matter in this example – 0___________ Jan 08 '20 at 15:12
  • @P__J__ I wrote that before I realised the pointer being added has the wrong type/increment. That part of the comment still applies, even if the type was correct. – underscore_d Jan 08 '20 at 15:13
  • Is there a way arround padding? like a compiler flag – Daniel Jan 08 '20 at 15:13
  • 1
    Yes, but it won't save you here, and nor should it. Again, why do you think this is the kind of code you should be writing? What problem are you trying to solve? There must be a better way. – underscore_d Jan 08 '20 at 15:13
  • I was curious if this would work – Daniel Jan 08 '20 at 15:19
  • I'm curious why you would want it to! – underscore_d Jan 08 '20 at 15:21
  • Does this answer your question? [Layout in memory of a struct. struct of arrays and array of structs in C/C++](https://stackoverflow.com/questions/8377667/layout-in-memory-of-a-struct-struct-of-arrays-and-array-of-structs-in-c-c) – gstukelj Jan 08 '20 at 15:24
  • Assuming that you want to access the next `int` in the struct through pointer arithmetic, then there is no formal guarantee that there's no padding in between. In practice though, it is very likely to work, portably, if the struct has the minimal alignment requirement of an `int` as in this case. – Lundin Jan 08 '20 at 15:32

1 Answers1

5

It will not for sure.

&example + sizeof(int) this operation moves the pointer sizeof(int) * sizeof(example) bytes ahead.

And this line will not compile at all

*(&example + sizeof(int)) = 33;

To know the offset of the particular field in the struct or union use offsetof

http://man7.org/linux/man-pages/man3/offsetof.3.html

0___________
  • 60,014
  • 4
  • 34
  • 74