繁体   English   中英

C如何修改其他结构中的结构的内存

[英]C how to modify memory of structs that are inside other structs

如果我有两个结构:

typedef struct{
    unsigned int time;
    double rate;

}quote;

typedef struct{

    unsigned int freeSlots;
    unsigned int end;
    unsigned int start;
    unsigned int currSize;
    unsigned int maxSize;
    unsigned int startAt;
    //unsigned int currIndex;
    quote quoteBuffer[1];

}cbuf;

我想创建一个函数来修改cbuf中的quoteBuffer数组的大小,我究竟会怎么做呢? 我尝试了一些方法,但到目前为止还没有。 我一直回到相同的格式:

quote *newQuoteBuffer = malloc(sizeof(quote) * newSize);

如果我已经有一个现有的cbuf(例如,我们将其称为“a”,其中a是指向cbuf的指针):

a->quoteBuffer = newQuoteBuffer;

但显然这不起作用。 任何提示?

这个:

quote quoteBuffer[1];

应该:

quote *quoteBuffer;

然后分配将起作用。

取消引用quote如下所示:

a->quoteBuffer->time;

如果您以后有多个使用malloc()分配的引用元素,您可以像这样访问它们:

a->quoteBuffer[i].time;

如果您不确定quoteBuffer中将包含多少元素,请维护相同的链接列表。 为了那个原因

quote *quoteBuffer;

并根据需要继续向缓冲区添加元素或从缓冲区中删除元素。

我认为你错过了为什么某人将结构的最后一个元素作为单个元素数组的观点。 这是一种在旧C代码中用作使结构大小可变长度的方法。

你可以编写如下代码:

Bitmapset *p = malloc(offsetof(Bitmapset, quoteBuffer) + n * sizeof(quote));

然后你编写这样的代码:

p->quoteBuffer[0]

取决于:

p->quoteBuffer[n-1]

正如您猜测的那样,您不希望将指针直接指定给quoteBuffer。

那么,为什么要将quoteBuffer声明为:quote quoteBuffer [1]; 而不是引用* quoteBuffer;

这是因为你不想为quoteBuffer单独分配。 单个分配可用于整个cbuf,包括内联引用数组。

有两种方法。 一种是在cbuf中使用指针,正如其他人提到的那样,通过改变

quote quoteBuffer[1];

quote* quoteBuffer;

另一种是调整cbuf的大小:

#include <stddef.h> // for offsetof

struct cbuf* realloc_cbuf(struct cbuf* cbufp, size_t nquotes)
{
    struct cbuf* new_cbufp = realloc(cbufp, offsetof(struct cbuf, quoteBuffer) + nquotes * sizeof *cbufp->quoteBuffer);
    if (!new_cbufp)
    {
        // handle out of memory here. cbufp is still intact so free it if you don't need it.
    }
    return new_cbufp;
}

void elsewhere(void)
{
    struct cbuf* acbuf = NULL;
    acbuf = realloc_cbuf(1);
    acbuf = realloc_cbuf(10);
    // etc. 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM