0

I have a struct that contains three int members:

struct ints{
    int int1;
    int int2;
    int int3;
};

I want to access the members of the struct using an int (*)[3] pointer:

ints i = {1,2,3};
int (*p)[3] = (int (*)[3])&i;
std::cout << (*p)[0] << std::endl;
std::cout << (*p)[1] << std::endl;
std::cout << (*p)[2] << std::endl;

This seems to work fine, but I'm not sure if this is undefined behavior according to the C++ standard. And what if I have a struct with four int members but I still use an int (*)[3] pointer?

iz0
  • 1
  • 1
    In general do notmake assumptions on memory layout (there can be padding/alignment etc), even though it might work on your system is no guarantee it will on another system. – Pepijn Kramer Mar 30 '23 at 15:15
  • 2
    It has undefined behaviour, like (almost) all situations where you access something through a pointer of the wrong type. – molbdnilo Mar 30 '23 at 15:16
  • As you're doing it (as other comments have implied and/or noted) you have undefined behaviour. (Which means, among other things, that even if your code seems to work, the standard doesn't actually offer a guarantee). In any event, why not have `struct ints {int data[3];};`? Then `ints i = {1,2,3}; int (*p)[3] = &(i.data);`, followed by your statements writing to `std::cout`, is perfectly valid (since `p` then *actually* points at an array of three `int`). And no need for any type conversions, since `i.data` is *actually* an array of three `int`. – Peter Mar 30 '23 at 15:34

0 Answers0