2b|!2b==? wrote:
I have a struct which holds an array of structs like this
struct Struct1
{
struct Struct2* strt2 ;
....
};
I allocate a predetermined size to hold n structs of type Struct2.
However, Struct2 represents data that is coming in from a feed. I want
to have an operation that "shifts" the array elements down by one when a
new packet (of type Struct2) is received, so that Struct1 ALWAYS
contains the latest n values.
memove comes to mind, but I'd appreciate some pointers (pun intended)
A "circular buffer" comes to mind. Keep the array at
the fixed size n (if n is really truly fixed, you might just
make strt2 an array instead of a pointer), and don't move
things around at all. Instead, keep an index k that tells
where the newest[*] item is. To insert a still newer item,
set k = (k + 1) % n and deposit the newer item there; it
will automatically overwrite the oldest item. To inspect
all the n newest items from newest to oldest, loop through
k, k-1, ..., 0, n-1, ..., k+1 (again, the % operator may
come in handy). To inspect them oldest to newest, loop on
k+1, ..., n-1, 0, ..., k.
[*] Variations: let the index point at the oldest item,
and/or use k = (k - 1) % n to run the index in the opposite
direction. Use whichever convention fits most neatly with
whatever else you're doing to the items.
--
Eric Sosman
es*****@acm-dot-org.invalid