Casting an int pointer to a char ptr and vice versa

18,764

There are big-endian and little-endian for CPUs, so the results are undefined. For example, the value of 0x01234567 could be 0x12 or 0x67 for a char pointer after casting.

Share:
18,764
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    The problem is simple. As I understand, GCC maintains that chars will be byte-aligned and ints 4-byte-aligned in a 32-bit environment. I am also aware of C99 standard 6.3.2.3 which says that casting between misaligned pointer-types results in undefined operations. What do the other standards of C say about this? There are also many experienced coders here - any view on this will be appreciated.

    int *iptr1, *iptr2;
    char *cptr1, *cptr2;
    
    iptr1 = (int *) cptr1;
    cptr2 = (char *) iptr2;