0

Following jldupont's answer on defining variables with varying data, I defined the following:

enum buffer_format
{ 
    FIFO_U8T = 0, 
    FIFO_U16T 
};

struct buffer_param
{
    enum buffer_format type;
    union
    {
        struct buffer_fifo_u8_t *fifo_u8;
        struct buffer_fifo_u16_t *fifo_u16;
    } is;
};

I then coded the following assignments:

struct buffer_param fifo_uartTx_param;
fifo_uartTx_param.is.fifo_u8 = &fifo_uartTx;
fifo_uartTx_param.type = FIFO_U8T;

However, I am met with some errors that complain that I can't simply reach into my buffer_param type struct to make these assignments. How would I assign the pointer to the UART fifo and set its type?

error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
 fifo_uartTx_param.is.fifo_u8 = &fifo_uartTx;
                  ^
error: expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
 fifo_uartTx_param.type = FIFO_U8T;
                  ^
  • Well, the compiler message is telling you exactly where the problem is. You need a dot `.` rather than an arrow `->` when accessing members of the `is` union. But what the compiler is not telling you is that you are also failing to allocate any memory for `fifo_uartTx_param` (you're declaring a pointer and then dereferencing that pointer without initializing it - this is undefined behavior and if you're lucky your program will just crash). – TypeIA Feb 26 '18 at 20:47
  • 1
    `fifo_uartTx_param->is` is not a pointer. So accessing it's fields is done with `.` – Eugene Sh. Feb 26 '18 at 20:47
  • There's probably no need to make `fifo_uartTx_param` a pointer, just make it an ordinary variable. Then use `.` in place of both `->`. – Barmar Feb 26 '18 at 20:59
  • I've made the changes as suggested (making `fifo_uartTx_param` into an ordinary variable and using `.` to access the struct fields) and am still receiving an error at compile time. – Chris Slothouber Feb 26 '18 at 21:03

1 Answers1

0

You're getting an error because you're attempting to do assignments outside of a function. Only definitions with an initializer are allowed.

To initialize this variable, do this:

struct buffer_param fifo_uartTx_param = 
    { .type = FIFO_U8T, .is= { .fifo_u8 = &fifo_uartTx } };
dbush
  • 205,898
  • 23
  • 218
  • 273