eszik.k
eszik.k

Reputation: 1781

Union declaration with array pointer?

I have the following union structure:

typedef union Message
{
  struct
  {
    unsigned short header: 16;
    unsigned short header2: 16;
    unsigned int timestamp: 32;
    unsigned int payload: 32;

  } pieces;
  unsigned short whole[6];
}Message;

If I declare this way it works

Message msg = {.whole={255,255,255,0,255,0}};

I am just wondering there is any solution to declare union by an exsisting array? Like this:

unsigned short arr[] = {255,255,255,0,255,0};
Message msg = {.whole=arr};

Upvotes: 1

Views: 55

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78923

No, that is not possible. Using the name of an array has it "decay" to a pointer to the first element in almost all contexts.

BTW, this has nothing to do with the fact that your array is hidden inside a union. Arrays can't be assigned to and the only way to initialize them is by using an initializer as you did.

You could just use memcpy to copy the contents, though.

Upvotes: 3

Related Questions