对于嵌入式应用程序,我正在尝试使用 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;
...然后编译器很高兴。但是,我担心错误消息暗示我在这里可能做错了一些微妙的事情。所以(直截了当),谁能告诉我为什么编译器不高兴,以及是否有更好的方法来做我想做的事情。