Is it possible to get a pointer to a full element of an object representation from a pointer to a subproject?

Consider this code:

int i;
int is[10]{};

unsigned char * p = reinterpret_cast<unsigned char*>(&i);
//p defined to point to the object-representation of the first element of array ints
unsigned char * ps = reinterpret_cast<unsigned char*>(&is[0]);

p += sizeof(int);
ps += sizeof(int);
//now ps points to the end of ints[0] and p point to the end of i;

p += sizeof(int); //Undefined behavior according to [expr.add]

ps += sizeof(int); //Undefined behavior?
unsigned char c = *ps;//Undefined behavior?

If we believe that it pspoints to a representation object is[0] , then according to the arithmetic rule of the pointer, the behavior is undefined in the last two lines of code.

However, if psit is also a pointer to an int array representation object is, then the behavior is determined.

So my question is: is a pointer to an object representing an object also a pointer to an element of an object representing a complete object?

+4
source share
2 answers

General case

, - - .

:

1.8/1: - .

3.9/4: T N char , T, N sizeof (T).

5.3.3/1: sizeof .

1.8/2: , . -, , . , .

, , , .

, .

, (.. ) - (.. ).

8.4.3/1: (...) N T. (...)

, :

  • , , .

  • unsigned (T), - N * sizeof (T).

:

  • , .

  • k- k- k * sizeof (T) .

, 2 undefined, is

+3

, " ". , , .

" " , , lvalue , .

reinterpret_cast<unsigned char*>(p) , - " ". .

+1

Source: https://habr.com/ru/post/1687467/