Search code examples
carraysunions

Assigning an array's head pointer to an existing array in a union, in C


I'd like to "equate" two arrays, where one is inside a fixed union (should not be changed). Instead of using memcpy, I'd simply point the head of myUnion.RawBytes to the head of array. But the compiler throws an error for the myUnion.RawBytes = &array[0]; assignmet. Why is this so? Is there any way I can circumvent this problem?

The faulty code below tries to illustrate this.

#include <stdio.h>

typedef union{
    unsigned char  RawBytes[2];
    unsigned short RawWord;
} MyUnion;

int main(){
    MyUnion myUnion;

    char array[2] = {1, 1};
    myUnion.RawBytes = &array[0];

    printf("%d", myUnion.RawWord);

    return 0;
}

Error:

main.c: In function ‘main’:
main.c:12:22: error: assignment to expression with array type
     myUnion.RawBytes = &array[0];

Solution

  • To solve your purpose you can use below approach.

    Note: Below approach doesn't follow strict aliasing rule.

    #include <stdio.h>
    
    typedef union{
        unsigned char  RawBytes[2];
        unsigned short RawWord;
    } MyUnion;
    
    int main(){
        MyUnion *myUnion;
    
        unsigned char array[2] = {1, 1};
        myUnion = &array;
    
        printf("%d", myUnion->RawWord);
        printf("\n%d %d", myUnion->RawBytes[0], myUnion->RawBytes[1]);
    
        return 0;
    }
    

    I strictly recommend you to have array inside union and use memcpy or for loop.