Search code examples
c++arrayscpointerspointer-arithmetic

Is it safe and portable to cast pointer to any type to char pointer for arithmetic?


Considering the following snippet, and for both C and C++ languages, is:

int t[2] = { 0, 1 };
*( (int *)( (char *)t + sizeof(int) ) ) = 2;

always equivalent to:

int t[2] = { 0, 1 };
t[1] = 2;

?

It might sound weird but I imagined some reasons why it could be false on some platforms:

  1. char pointer increment could go in a reverse way than int pointer, unless it is not authorized by the standard (in this case I would like to find where the standards states so)

  2. the cast from int * to char * could be unsafe because there is not guaranty that their size are the same (and in this case, could it work with an intermediate cast to void *?), and because the standard does not guaranty that casting to char * and then to a pointer to any type is safe


Solution

  • Is it safe and portable to cast pointer to any type to char pointer for arithmetic?

    Any type --> No.

    (Non-null) function pointers cast to char * is UB and then math applied is UB.

    A char * may even be too small to encode a function pointer.