【发布时间】:2026-02-11 06:55:02
【问题描述】:
在寻找可重用的循环缓冲区代码时,我遇到了一个让我困惑的 char 用法
typedef struct CircularBuffer
{
void *buffer; // data buffer
void *buffer_end; // end of data buffer
size_t capacity; // maximum number of items in the buffer
size_t count; // number of items in the buffer
size_t sz; // size of each item in the buffer
void *head; // pointer to head
void *tail; // pointer to tail
} CircularBuffer;
void cb_push_back(CircularBuffer *cb, const void *item)
{
if(cb->count == cb->capacity)
// handle error
memcpy(cb->head, item, cb->sz);
////////////// here's the part I don't understand //////////
cb->head = (char*)cb->head + cb->sz;
//////////////////////////////////////////////////////////
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
cb->count++;
}
为什么要将此 void 指针转换为 char?这是某种 C 习语吗(我的 C 经验非常有限)?也许是一种增加指针的便捷方法?
在一些不同的缓冲区代码中也再次出现使用 char 作为位置指针:
/**< Circular Buffer Types */
typedef unsigned char INT8U;
typedef INT8U KeyType;
typedef struct
{
INT8U writePointer; /**< write pointer */
INT8U readPointer; /**< read pointer */
INT8U size; /**< size of circular buffer */
KeyType keys[0]; /**< Element of ciruclar buffer */
} CircularBuffer;
再一次,这看起来像是 C 程序员知道的某种方便的技巧,如果指针是字符,那么指针很容易操作。但我真的只是在猜测。
【问题讨论】:
-
仅供参考:该类型称为
char*,而不是*char。 -
这是我第一次看到struct的名字是typedef的名字,这很奇怪……