对于嵌入式应用程序,我尝试使用 ANSI C 实现先进先出 (FIFO) 结构队列。最直接的方法似乎是通过实现链表,以便每个结构包含指向队列中下一个的指针。因此我将结构本身定义为:
typedef enum { LED_on, LED_off, etc } Action;
typedef struct Queued_Action QueuedAction;
struct Queued_Action
{
Action action;
int value;
QueuedAction *nextAction;
};
到目前为止,一切都很好。如果我将指向队列中第一个和最后一个项目的指针定义为:
QueuedAction *firstAction;
QueuedAction *lastAction;
...然后我希望能够通过说明(例如)将新操作添加到队列中:
if (!add_action_to_queue(LED_on, 100, &lastAction))
printf("Error!\n);
...所以返回时,lastAction 将是指向队列中新创建的最后一个操作的指针。因此,将操作添加到队列的例程如下所示:
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;
}
一切都会好起来的,除了这段代码无法编译。错误是在行说
*lastAction -> nextAction = newQueuedAction;
...编译器声称“->”左侧的项目不是有效的结构。然而,确实必须如此。如果事实上我做了应该完全多余的转换:
fakeAction = (QueuedAction *)(*lastAction);
fakeAction -> nextAction = newQueuedAction;
...那么编译器就很高兴了。然而,我担心错误消息暗示着我可能在这里做错了一些微妙的事情。所以(言归正传),谁能告诉我为什么编译器不高兴,以及是否有更好的方法来完成我在这里尝试做的事情。