如何纠正圆形数组插入中的索引

时间:2017-09-14 15:03:15

标签: c producer-consumer

我正在尝试在动态循环数组中找到插入前置的公式。我遇到的一个问题是当尝试运行显示时,前两次插入后的inx将关闭,因为有一个未占用的索引。这假设我遵循选择起始索引的正确方法。

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",")");
    }
}

1 个答案:

答案 0 :(得分:0)

听起来你正试图制作一个环形缓冲区...这是一个学术起点:

#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);
}