at_yasu's blog

ロード的なことを

保守メモ -- UNION --

C言語で、あたしがつい最近まで理解できなかった共用体の使用例。

#include <stdio.h>

union uniColor {
    unsigned int rgbaColor;
    unsigned char rgba[4];
} color;

int main (void)
{
    union uniColor color;
    color.rgbaColor = 0x8aA8baff;
    fprintf (stdout, "R[%d], G[%d], B[%d], A[%d]\n",
            color.rgba[0],
            color.rgba[1],
            color.rgba[2],
            color.rgba[3]);

    return 0;
}

簡単に説明。unionは構造体と同じ文法で使う。ただ、動作は構造体とは全然違う。
構造体の場合、各要素ごとにデータ領域を持って、それぞれ別々のデータを持っている。
一方、共用体の場合、データ領域は同じ部分を表していている。

上の例だと、rgbaColorとrgbaは同じデータを指している。下記のはメモリー上のデータ領域。

          |0 1 2 3 4 5 6 7 | 9 a b c d e | 0 1 2 3 4 5 6 7 | 9 a b c d e |
rgbaColor |------------------------------------------------------------->|
rgba      |        0       |      1      |         2       |      3      |

つまり、上のプログラムでは、rgba[0]は8a、rgba[1]はA8、rgba[2]はba、同様にrgba[3]ではffが入っている。


参考:http://www.geocities.jp/ky_webid/c/047.html

# union と聞いて、onion を思い浮かべてしまう (^^;