MC Potgieter

Data sets inside a union

Discussion created by MC Potgieter on Feb 2, 2008
Latest reply on Feb 4, 2008 by CrasyCat

I want to make a union of to data sets (a structure and an array).

My code is as follows:

#define COMMS_BUFFER_SIZE 80
#define PROTOCOL_HEADER_SIZE 5
#define PROTOCOL_DATA_SIZE (COMMS_BUFFER_SIZE - PROTOCOL_HEADER_SIZE)

typedef struct {
  u8 StartByte;
  u8 Route;
  u8 Command;
  u8 Length;
  u8 HCS;
  u8 Data[PROTOCOL_DATA_SIZE];
}TProtocol;

typedef union {
  TProtocol Protocol;
  u8 Data[COMMS_BUFFER_SIZE];
}TCommsBuffer;

extern TCommsBuffer CommsBuffer;

I want to access the contents of "TCommsBuffer" in the protocol format (strucrure) or as a array.

CommsBuffer.Data[x] = x;
CommsBuffer.Protocol.StartByte = x;

But it gives me problems.

When I read data into the Protocol structure, it repeats the contents of the 1st 5 bytes of the protocol structure into its data section.

Is this the correct way to define the union?

Outcomes