Character types cannot be accessed through non-character types.

suggest change

If an object has static, thread, or automatic storage duration and a character type (char, unsigned char, or signed char), its stored value may not be accessed through an incompatible type such as int. In the example below, a char array is reinterpreted as int. The conversion is undefined if the array is not correctly aligned for int, and each dereference of b is also undefined under the effective-type rules. _Thread_local is the C11 spelling; C23 also provides thread_local as a keyword.

int main( void )
{
    char a[100];
    int* b = ( int* )&a;
    *b = 1;      

    static char c[100];
    b = ( int* )&c;
    *b = 2;

    static _Thread_local char d[100];
    b = ( int* )&d;
    *b = 3;
}

This is undefined because it violates the effective-type rule. An object with a declared character type may be inspected through a character type, but not through an incompatible type such as int.

Even if alignment and pointer sizes would be known to fit, this would not exempt from this rule, behavior would still be undefined.

This means in particular that there is no way in standard C to reserve a buffer object of character type that can be used through pointers with different types, as you would use a buffer that was received by malloc or similar function.

A correct way to achieve the same goal as in the above example would be to use a union.

typedef union bufType bufType;
union bufType {
   char c[sizeof(int[25])];
   int i[25];
};

int main(void)
{
    bufType automatic_buffer = { .c = { 0 } };
    int *automatic_view = automatic_buffer.i; /* No cast is necessary. */
    *automatic_view = 1;

    static bufType static_buffer = { .c = { 0 } };
    int *static_view = static_buffer.i;
    *static_view = 2;

    static _Thread_local bufType thread_buffer = { .c = { 0 } };
    int *thread_view = thread_buffer.i;
    *thread_view = 3;
}

Here, the union type includes both views, so storing through the int member is defined. That member already has type int[25], so no pointer conversion is required.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents