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. 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. A FIFO is an abstract data type that has two behaviors:
A FIFO implement should keep track up its beginning and its end, so let's update your FIFO struct.
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. (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 . Many people prefer a linked list based FIFO that would have a struct like this:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.