简体   繁体   English

访问 typedef 结构中的列表

[英]Accessing a list in typedef struct

typedef char Word[ WORD_LEN + 1 ];

typedef struct {
    Word list[ MAX_WORDS ];

} FIFO;

So I have a pointer to a FIFO struct, and I'm curious as to what the best way is to access the list inside.所以我有一个指向 FIFO 结构的指针,我很好奇访问内部列表的最佳方法是什么。 I have to be able to add and remove words from the list.我必须能够在列表中添加和删除单词。 Any help would be awesome, thanks!任何帮助都会很棒,谢谢!

Let's talk about your choices for representing a FIFO, which will clear up your confusion about how to access the data.让我们谈谈您对表示 FIFO 的选择,这将消除您对如何访问数据的困惑。 A FIFO is an abstract data type that has two behaviors: FIFO 是一种抽象数据类型,具有两种行为:

  1. Items are removed from the beginning.项目从一开始就被删除。
  2. Items are added to the end.项目被添加到最后。

A FIFO implement should keep track up its beginning and its end, so let's update your FIFO struct. FIFO 工具应该跟踪它的开始和结束,所以让我们更新你的 FIFO 结构。

typedef struct {
    unsigned int begin; /* index to first element */
    unsigned int end; /* index to last element */
    Word list[ MAX_WORDS ];
} FIFO;

Now, we need two functions that implement the two behaviors above.现在,我们需要两个函数来实现上述两种行为。 Let's call them fifo_add and fifo_remove.我们称它们为 fifo_add 和 fifo_remove。 (These are incomplete) (这些是不完整的)

void fifo_add(FIFO * fifo, Word w)
{
    fifo.list[fifo->end] = w;
    fifo->end++;
}

Word fifo_remove(FIFO * fifo)
{
    int i = fifo->begin;
    fifo->begin++;

    return fifo->list[i];
}

I've purposefully left these functions incomplete, but I hope this gets you thinking in the right direction (see this page about circular buffers ).我故意让这些函数不完整,但我希望这能让您朝着正确的方向思考(请参阅有关循环缓冲区的页面)。 I need to stress that this is only one possible implementation of a FIFO .我需要强调的是,这只是 FIFO 的一种可能实现 Many people prefer a linked list based FIFO that would have a struct like this:许多人更喜欢基于链表的 FIFO,它具有如下结构:

typedef struct {
    Word w;
    Node * next;
} Node;

typedef struct {
    Node * head;
    Node * tail;
} FIFO;

Regardless of what implementation you use, the fifo_add and fifo_remove will have the same interface, which isolates your FIFO code from the rest of your program.无论您使用何种实现,fifo_add 和 fifo_remove 都将具有相同的接口,这将您的 FIFO 代码与程序的其余部分隔离开来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM