【发布时间】:2017-07-04 07:02:03
【问题描述】:
我尝试用 C 语言通过数组和指针来实现队列。队列 采用C结构建模
// Circular Buffer
typedef struct{
main_controller_req_t buffer[BUFFER_SIZE]; // buffer
uint16_t size; // length of the queue
uint16_t count; // number of elements present in the queue
main_controller_req_t *p_head; // pointer to head of the queue (read end)
main_controller_req_t *p_tail; // pointer to tail of the queue (write end)
}circular_buffer_t;
我已经实现了队列初始化函数
void init_cb(circular_buffer_t *p_cb){
p_cb->p_head = p_cb->buffer;
p_cb->p_tail = p_cb->buffer;
p_cb->count = 0;
p_cb->size = BUFFER_SIZE;
}
插入队列的函数
BOOL enqueue_cb(circular_buffer_t *p_cb, main_controller_req_t *p_enq_elem){
if(p_cb->count < p_cb->size){
// queue contains at least one free element
taskENTER_CRITICAL();
// insert the element at the tail of queue
*(p_cb->p_tail) = *p_enq_elem;
// incrementing modulo size
p_cb->p_tail = (((p_cb->p_tail++) == (p_cb->buffer + p_cb->size)) ? (p_cb->buffer) : (p_cb->p_tail));
// one element added
p_cb->count++;
taskEXIT_CRITICAL();
return TRUE;
}else{
// queue is full
return FALSE;
}
}
enqueue_cb 函数运行良好,直到尾部达到 BUFFER_SIZE。然后 程序崩溃和 uC 重置。问题出在 p_tail 指针更新中,但我没有 明白为什么。请问有人可以帮我吗?提前致谢。
【问题讨论】:
-
我建议您在您的 PC(Visual Studio 或类似软件)上执行所有不依赖于 CPU 的库。它将简化您的调试并产生更少的问题。
-
请提供您的主要功能的一小部分,您的使用会导致崩溃。
-
@Steve> 您不能在同一语句中指定 p_cb->p_tail 和在其上使用
++。 (公平地说,你可以让你的代码难以理解,即使是你自己)
标签: c arrays pointers struct queue