通过n个元素循环移动动态c数组

时间:2012-08-30 12:00:14

标签: c arrays dynamic queue shift

我有一个设置长度的队列,实现为像这样实现的动态c数组:

typedef struct {
    float* queue;
    int size;
    int pointer;
} QueueStruct;

void createQueue(QueueStruct* queueInstance, int size){
    queueInstance->queue = malloc(sizeof(float)*size);
    queueInstance->size = size;
    queueInstance->pointer = 0;
}

void addElementToQueue(QueueStruct* queueInstance,float element){
    queueInstance->queue[pointer] = element;
    if (queueInstance->pointer == queueInstance.size - 1){
        queueInstance->pointer = 0;
    } else {
        ++queueInstance->pointer;
    }
}

void freeQueue(QueueStruct* queueInstance){
    free(queueInstance->queue);
}

我想实现这个功能:

float* returnQueue(QueueStruct queueInstance){
    //I want this function to malloc a new float* and then put the queue in it in the
    // correct order, from start to finish, as pointed too by the pointer.  
    //Im not sure how to do this.
}

任何帮助都将不胜感激。

编辑:纠正了一个愚蠢的编程错误 - 这是我程序中实际内容的简化版本。

3 个答案:

答案 0 :(得分:2)

让我们看看我是否做对了。

float* returnQueue(QueueStruct *queueInstance){
    int j = 0;
    float *ret = malloc(sizeof(float)*queueInstance->size);  //Allocates the memory you want.
    //Copies the elements from pointer to End into the new buffer (assumes, that the array has been filled at least once, add a marker to make sure)
    if(queueInstance->FilledOnce) { //Marker variable, explanation as above.
        for(int i = queueInstance->pointer; i < queueInstance->size; ++i, ++j)
            ret[j] = queueInstance->queue[i];
    }
    //Copies the newest elements (from beginning to pointer) into the buffer.
    for(int i = 0; i < queueInstance->pointer; ++i, ++j)
        ret[j] = queueInstance->queue[i];
    return ret; //Returns the code in question.
}

要使此代码正常工作,您必须在结构中添加“FilledOnce”,并修改“添加”代码,如下所示:

void addElementToQueue(QueueStruct* queueInstance, float element){
    queueInstance->queue[queueInstance->pointer] = element;
    if (queueInstance->pointer == queueInstance.size - 1){
        queueInstance->pointer = 0;
        queueInstance->FilledOnce = 1;
    } else {
        ++queueInstance->pointer;
    }
}

我还建议你,一旦完成变量就重置你的变量。

void freeQueue(QueueStruct* queueInstance){
    free(queueInstance->queue);  //Frees the queue
    queueInstance->queue = NULL; //Nulls the reference
    queueInstance->FilledOnce = 0;
    queueInstance->pointer = 0;
    queueInstance->size = 0;
}

这样,如果重用结构,就不会遇到尝试访问未分配内存的问题。请务必检查这些变量。

我希望这会有所帮助。

答案 1 :(得分:0)

我认为你也应该为你的结构分配内存。 你已经创建了struct的指针但是忘了为该结构分配内存

使用QueueStruct queuestruct = malloc(sizeof(Queuestruct))

然后当你将它传递给上面的任何函数时,你可以轻松分配 队列poiter的内存,您可以在其中存储队列数组的元素

答案 2 :(得分:-1)

此实施不足。一个pointer变量给我们一个队列尾部的位置,但是什么指向它的头部?

相关问题