How to Implement a Dynamic Circular Chasing Pointer Array of Integers?

  • Thread starter Thread starter Rocket254
  • Start date Start date
  • Tags Tags
    Circular Pointers
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 3K views
Rocket254
Messages
33
Reaction score
0
Circular chasing pointers...

Can anyone please point me towards a site that can explain how to implement a dynamic circular chasing pointer array of integers?

Thanks in advance
 
Physics news on Phys.org
I'm guessing here, but it sounds like you want to create a circular fifo using pointers (indexes could also be used, with no additional overhead on an Intel CPU, but possibly more overhead on other CPUs).

Code:
// for multi-tasking, a common mutex should be used in these functions
// if there's no need for overflow checking, iNumElements can be removed,
//    and an empty array is indicated when pGet == pPut

// if PutElement returns a 1, the array just went from empty to non-empty.

#define MAXSIZE 1024 // up to 1024 integers 

static          int aIntegers[MAXSIZE];
static constant int *pBase = &aIntegers[0];
static constant int *pEnd  = &aIntegers[MAXSIZE];
static          int *pPut  = &aIntegers[0];
static          int *pGet  = &aIntegers[0];
static          int iNumElements = 0;

int PutElement(int iElement)
{
    if(iNumElements == MAXSIZE)    // prevent overflow, caller code should check this
        return;
    *pPut++ = iElement
    if(pPut >= pEnd)
        pPut = pBase;
    iNumElements += 1;
    return(iNumElements);
}

int GetElement(void)
{
int iValue;

    if(iNumElements == 0)    // return 0 if empty array, calling code should do this check
        return(0);
    iNumElements -= 1;
    iValue = *pGet++;
    if(pGet >= pEnd)
        pGet = pBase;
    return(iValue);
}

int PeekElement(void)
{
    if(iNumElements == 0)    // return 0 if empty array, calling code should do this check
        return(0);
    return(*pGet);
}
 
Last edited: