In following code sample, how can I make *y to point to offset 4?
Right now, only points to offset 0, which is for *x, not *y.
(note that *x & *y will have 4 bytes each)
unsigned char *p = new unsigned char[8];
int *x = &*(int *) p;
*x = 1;
int *y = &*(int *) p;
*y = 2;
Please dont talk about struct or other ways, they won’t help me.
If you are actually storing multiple types in a contiguous buffer, you might be in for a world of pain when it comes to alignment issues. Not all types can be aligned on the same memory boundaries: some might need to be 32-bit aligned, some 64-bit, some 128-bit, and this is all platform-dependent.
Some reading to get you started, but you should read a lot more including the alignment of user-defined types, and for the various compilers and operating systems you are targeting if you really want to do this the way you are doing without using a more structured approach (ex: Variant type approaches combining static and dynamic polymorphism).
In fact, the kind of material you need to understand if you want to do this is quite similar to what you have to learn about data alignment when implementing your own memory allocator (a general memory allocator has to deal with being able to store multiple types in contiguous buffers), so searching for similar topics may give you what you need. I can’t help but say that this low-level problem may give you and any co-workers a lot more grief than anyone should ever deserve.
You need to know what types need to be aligned to what boundaries (byte, word, doubleword, quadword). It varies as well. You can’t necesarily store an int that isn’t aligned on word boundaries, for example. On some systems this might take a huge performance penalty for unaligned moves or even crash your program. This is also why structs typically have padding inside to make sure all data is aligned correctly.
However, for your immediate example which isn’t mixing types (just integers):