实现在C FIFO队列 [英] Implementing a FIFO queue in C
问题描述
对于嵌入式应用,我想实现一个先入先出(FIFO)队列似乎是通过实施链表,使每个结构包含一个指向队列中的下一个。因此,我定义了结构本身:
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);
...等的回报,lastAction将是一个指向队列中的新创建的最后一个动作。因此,对于加入行动队列程序会是这样的:
...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;
}
所有将被罚款和花花公子,但这次code将无法编译。该错误是在该行称
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.
推荐答案
你试过:
(*lastAction) -> nextAction = newQueuedAction;
这篇关于实现在C FIFO队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!