将动态 c 数组循环移位 n 个元素

标签 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.
}

如有任何帮助,我们将不胜感激。

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

最佳答案

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

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

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

希望对您有所帮助。

关于将动态 c 数组循环移位 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12196377/

相关文章:

c - 如何从函数中的数组返回结构? (指针)

c - 确定输入是否是 C 中的回文

Java代码优化与安全

python - 不使用 for 循环的子数组的点积

php - 如何使用动态页面的索引号链接到页面

WPF Image 在运行时动态更改图像源

iphone - 是否可以在 iPhone 项目中使用一些 C 源代码?

c - 如果所有条件都成立就做某事

javascript - 如何计算JavaScript数组中变量重复的次数?

动态浮图图 - 通过单击图上的图例文本或框来显示隐藏系列