Reputation: 10284
Ok I have a struct defined as such...
typedef struct
{
enum COMMAND command;
enum CMD_SOURCE source;
CHAR parameters[16];
} focuserCommand;
I am trying to make a function that will add an instance of this type of struct to an array of focuserCommands. The array is defined like this...
extern focuserCommand CommandBuffer[CMD_BUFFER_SIZE];
the function I am trying to write should take a pointer to a focuserCommand
and add it to CommandBuffer
. I am implementing CommandBuffer as a FIFO ring buffer so I know i need to move the tail forwared so that my other functions can see that the buffer contains data. CmdBuffHead and CmdBuffTail represent the read and write pointers of the buffer. Writes are added to the tail, reads are made from the head.
void AddCmdToBfr( focuserCommand * cmd )
{
// What goes here to add the struct pointed to by cmd to
// element CmdBuffTail of the buffer?
CmdBuffTail++;
}
Upvotes: 0
Views: 4257
Reputation: 753555
Given that you have the variable CmdBuffTail
pointing at the next element of CommandBuffer
to be written to, then:
void AddCmdToBfr(focusCommand *cmd)
{
assert(CmdBuffTail >= 0 && CmdBuffTail < CMD_BUFFER_SIZE);
CommandBuffer[CmdBuffTail++] = *cmd;
if (CmdBuffTail >= CMD_BUFFER_SIZE)
CmdBuffTail = 0;
}
This preserves the invariant that you need - that the index is in the range 0..CMD_BUFFER_SIZE-1.
You may also need a separate index (CmdBuffHead
perhaps) to identify where to read from. If so, you would probably need to alter that value in AddCmdToBfr()
if CmdBuffTail
if catches up with it.
After fixing a goof copying the incoming command, it occurs to me that you need to think carefully about the memory management. In this case, your focususerCommand
structure is simple enough (unless the typedef CHAR
hides a pointer - in which case, slap wrists; don't hide pointers) that you can simply copy it with impunity. If you can't copy the structure simply (because it contains pointers to allocated memory), then you need to ensure you understand who owns the data to make sure that (a) any allocated memory is released, and (b) any allocated memory is released just once. This would mean, for example, that instead of just copying the new command over the old, you would have to first release the memory allocated to the old entry. Think in terms of C++ copy constructors and destructors - in C.
Upvotes: 1