我正在尝试开发一个使用两个结构的动态分配的C循环缓冲区。一个拥有详细信息,另一个主要用作从主循环到缓冲区结构的指针(因为在运行时会分配多个数组)。C - 动态地分配结构中的结构的循环缓冲区
由于它是一个圆形缓冲器,我有一个指针“下一个”,它指向该阵列中的下一个项目(所以最后一个数组索引指向所述第一等)
这是两个结构对象我有:
typedef struct {
int a;
int b;
struct1 *next; // pointer to next struct1 object in array
} struct1;
typedef struct {
struct1 *curr;
struct1 *start = NULL;
struct1 *end = NULL;
} struct2;
然后,我有我的初始化函数,从main调用来启动一个新的循环缓冲区。
这是我不完全确定要做什么的部分。
#define minSize 10
struct2 * initialize()
{
struct2 **newBuf = malloc(sizeof(*newBuf));
newBuf->malloc(sizeof(*newBuf->quotes) * newBuf->minSize);
// set the start pointer
newBuf.curr[0] = newBuf->start;
newBuf.curr[0]->next = NULL;
for (int i = 1; i < minSize; i++)
{
struct1 *new = NULL;
newBuf.curr[i] = new; // make index i = NULL
// have the previous index point to the "next" current
if (i > 0)
newBuf.curr[i-1]->next = newBuf.curr[i];
}
// connect last index with first
newBuf.curr[minSize - 1]->next = newBuf.curr[0];
// set the end pointer
newBuf->end = newBuf->start;
return newBuf;
}
从搜索,我发现this answer on how to initialize an array of structs within a struct通过使用malloc为最初分配的空间,但也很困惑我的代码将如何排队,因为我有一个指针来定义开始并在限定的圆形缓冲的年底 struct2,以及下一个指针作为struct1的一部分。
此外,我选择了定义*** newBuf *而不是** newBuf *,因为我正在考虑它作为指针的指针(考虑单链表)。虽然,如果我错了,请纠正我。
我已经完成了Java中动态分配的循环缓冲区,但不是C和C++,所以我很难弄清楚如何初始化所有内容。我基本上被困在这个混乱,不知道下一步去哪里。
任何可以给予的帮助将不胜感激!
'typedef结构{ struct1 CURR []; '不计算。请发布真实的代码。也许你会得到真正的答案。 – wildplasser 2013-04-07 23:24:22
是的,wildplasser:http://en.wikipedia.org/wiki/Typedef – 2013-04-07 23:35:27
没有@RobG。 OP *可能意味着一个VLA,但它仅作为结构中的最后一个元素有效。无论如何:他纠正了它。结论:它是*不是真实的代码*。 – wildplasser 2013-04-07 23:43:49