对于嵌入式应用程序,我试图使用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;
};
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.如果我将指向队列中第一个和最后一个项目的指针定义为:
QueuedAction *firstAction;
QueuedAction *lastAction;
Run Code Online (Sandbox Code Playgroud)
...然后我希望能够通过声明(例如)向队列添加新动作:
if (!add_action_to_queue(LED_on, 100, &lastAction))
printf("Error!\n);
Run Code Online (Sandbox Code Playgroud)
...所以在返回时,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;
}
Run Code Online (Sandbox Code Playgroud)
一切都很好,花花公子,除了这个代码不会编译.错误是在线说
*lastAction -> nextAction = newQueuedAction;
Run Code Online (Sandbox Code Playgroud)
...编译器声称" - >"左侧的项目不是有效的结构.当然,它一定是.如果事实上我做了什么应该是一个完全多余的演员:
fakeAction = (QueuedAction *)(*lastAction);
fakeAction -> nextAction = newQueuedAction;
Run Code Online (Sandbox Code Playgroud)
...然后编译器非常高兴.但是,我担心错误消息暗示了一些微妙的东西,我可能在这里做错了.所以(为了达到目的),任何人都可以告诉我为什么编译器不满意,以及是否有更好的方法来做我在这里尝试做的事情.
归档时间: |
|
查看次数: |
13392 次 |
最近记录: |