0

I am trying to find a formula for insert front in a dynamic circular array. One problem I have is when try to run display in which case the inx after the first two insertion will be off because there is an unoccupied index. This is assuming that I am following the correct way of choosing the start index.

void insertCDAfront(CDA *items,void *val){//insert in the slot prior t         
    assert(items->array!=0);
    if(sizeCDA(items)==0){
        items->array[items->start]=val;
        items->size++;

    }
    else{   

        if(items->size==items->capacity){
            items->capacity=items->capacity*items->factor;
            void **arr=calloc(items->capacity,sizeof(void *));
            assert(arr!=0);
            for(int i=0;i<items->size;i++){
                arr[i]=getCDA(items,i);

            }
            items->array=arr;
            items->start=0;

        }

        items->start=(items->start-1+items->capacity)%items->capacity;
        items->array[items->start]=val;
        items->start=0;

        items->size++;
    }
}


void *getCDA(CDA *items,int index){//
    assert (index<items->size&&index>=0);
    int spot=(items->start+index+items->capacity)%items->capacity;
    return items->array[spot];
}

void displayCDA(FILE *f,CDA *items){
    int i=0;
    if (items->size==0){
        fprintf(f,"("")");
    }
    else if (items->size==1){
        fprintf(f,"(");
        items->display(f,items->array[i]);
        fprintf(f,")");
    }
    else{
        fprintf(f,"%s","(");
        while (i!=items->size-1){     //i!=end
            items->display(f,getCDA(items,i));
            fprintf(f,"%s",",");
            i++;
        }

        items->display(f,getCDA(items,i));
        fprintf(f,"%s",")");
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
mokarab
  • 13
  • 1
  • 2
  • 4

1 Answers1

0

sounds like you are trying to make a ring buffer... Here's an academic starting point:

#define PREDETERMINED_ERROR_VALUE  (0)
#define MAX_SIZE                   (100)
int ring_buffer[MAX_SIZE] = {0};
unsigned int head = 0;
unsigned int tail = 0;

void add_item(int new_data)
//!\todo check for overrun
{ring_buffer[head++] = new_data;}

unsigned int get_size_of_ring_buffer(void)
{
unsigned int ret;
if tail <= head
    ret = head - tail;
else
    ret = head + MAX_SIZE - tail;
return (ret);
}

int get_item(void)
{
//!\todo consider returning error code and modifying a param with the data
int ret;
if (tail != head)
    ret = ring_buffer[tail++];
else
    ret = PREDETERMINED_ERROR_VALUE;
return (ret);
}
grambo
  • 283
  • 2
  • 10