tags:

views:

118

answers:

2

For an embedded application, I am trying to implement a first-in, first-out (FIFO) queue of structs using ANSI C. The most straightforward way to do this seems to be by implementing a linked-list, so that each structure contains a pointer to the next in the queue. Hence I define the struct itself as:

typedef enum { LED_on, LED_off, etc } Action;
typedef struct Queued_Action QueuedAction;

struct Queued_Action
{
    Action       action;
    int          value;
    QueuedAction *nextAction;
};

So far so good. If I define pointers to the first and last items in the queue as:

QueuedAction *firstAction;
QueuedAction *lastAction;

...then I'd like to be able to add a new action to the queue by stating (for example):

if (!add_action_to_queue(LED_on, 100, &lastAction))
     printf("Error!\n);

...so on return, lastAction would be a pointer to the newly-created last action in the queue. Hence the routine for adding the action to the queue would look like:

int add_action_to_queue(Action newAction, int newValue, QueuedAction **lastAction)
{
    QueuedAction *newQueuedAction;

    // Create a new action in memory
    if ((newQueuedAction = (QueuedAction *)malloc(sizeof(QueuedAction))) == NULL)
        return 0;

    // Make the old 'lastAction' point to the new Action, 
    // and the new Action to point to NULL:
    *lastAction -> nextAction = newQueuedAction;
    newQueuedAction -> nextAction = NULL;
    newQueuedAction -> action = newAction;
    newQueuedAction -> value = newValue;

    // Designate the new Action as the new lastAction:
    *lastAction = newQueuedAction;
    return 1;
}

All would be fine and dandy, except this code won't compile. The error is at the line saying

*lastAction -> nextAction = newQueuedAction;

...where the compiler claims the item to the left of the '->' is not a valid struct. Surely, however, it must be. If in fact I do what ought to be a wholly redundant cast:

fakeAction = (QueuedAction *)(*lastAction);
fakeAction -> nextAction = newQueuedAction;

...then the compiler is quite happy. However, I'm worried that the error message is hinting at something subtle that I may be doing wrong here. So (to come to the point), can anyone tell me why the compiler isn't happy, and whether there is a better way to do what I'm trying to do here.

Many thanks,

Stephen.

+2  A: 

Have you tried:

(*lastAction) -> nextAction = newQueuedAction;
mouviciel
I cant even read as fast as you answer ;-)
frast
Thank you both; it was indeed an issue of operator precedence, and putting the brackets around (*lastAction) solves the problem.
Eos Pengwern
+3  A: 

You could also do this:

(*lastAction)->nextAction

I think it is an issue of operator pecedence.

frast
Yep, that's operator precedence biting you.
sbi