我正在尝试使用两个结构在 C 中开发动态分配的循环缓冲区。一个保存详细信息,另一个本质上用作从 main 到循环缓冲区结构的指针(因为在运行时将分配多个数组)。
因为它是一个循环缓冲区,所以我有一个指针“next”,它指向数组中的下一个项目(因此最后一个数组索引指向第一个,等等)
这是我拥有的两个结构对象:
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 中定义的循环缓冲区的 start 和 end 的指针,以及作为 struct1 一部分的 next 指针。
此外,我选择定义 ***newBuf* 而不是 **newBuf*,因为我在某种程度上将其视为指向指针的指针(考虑单链表)。不过,如果我错了,请纠正我。
我已经在 Java 中完成了动态分配的循环缓冲区,但没有在 C 或 C++ 中完成,所以我很难弄清楚如何初始化所有内容的差异。我基本上陷入了困境,不知道下一步该去哪里。
如果您能提供任何帮助,我们将不胜感激!
最佳答案
你遇到麻烦的原因是因为你试图让指针指向一个指针,而不是仅仅使用一个普通的指针。您想要访问第一个指针所指向的地址中包含的指针。就目前情况而言,您正在尝试访问原始指针地址(仅与地址一样大)的内存空间之外的成员。然后你就会遇到麻烦,因为你也没有初始化数组“curr”。我做的另一件事并不重要,但可以帮助你理解指针,那就是让你的数组成为一个指针——这就是数组在 C 中的工作方式。数组只是数组第一个成员的地址,当你索引到数组,它只是向该地址添加一个偏移量 = index * sizeof(yourstruct)。
你想要的是
typedef struct {
struct1 *curr;
struct1 *start = NULL;
struct1 *end = NULL;
} struct2;
#define minSize 10
struct2* initialize()
{
struct2 *newBuf = (struct2 *) malloc(sizeof(struct2));
newBuf->curr = (struct1 *) malloc(sizeof(struct1) * minSize);
// set the start pointer
newBuf.curr[0] = newBuf->start;
newBuf.curr[0]->next = NULL;
for (int i = 1; i < minSize; i++)
{
struct1 *new = (struct1 *) malloc(sizeof(struct1));
newBuf.curr[i] = new;
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;
}
关于C - 在结构内动态分配结构的循环缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15869039/