C如何修改其他结构中的结构的内存
如果我有两个结构:C如何修改其他结构中的结构的内存,c,arrays,struct,C,Arrays,Struct,如果我有两个结构: 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;
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的指针):
但很明显,这是行不通的。有什么提示吗?这是:
quote quoteBuffer[1];
应该是:
quote *quoteBuffer;
那么作业就行了
取消引用quote
如下所示:
a->quoteBuffer->time;
a->quoteBuffer[i].time;
p->quoteBuffer[0]
如果以后使用malloc()分配了quote的多个元素,则可以如下方式访问它们:
a->quoteBuffer->time;
a->quoteBuffer[i].time;
p->quoteBuffer[0]
如果您不确定quoteBuffer中将包含多少元素,请维护相同元素的链接列表。为此
quote *quoteBuffer;
并根据需要不断在缓冲区中添加或删除元素。有两种方法。一种是在cbuf中使用指针,正如其他人所提到的,通过改变
quote quoteBuffer[1];
到
另一个是调整cbuf的大小:
a->quoteBuffer = newQuoteBuffer;
#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.
}
#包括//用于抵消
结构cbuf*realloc\u cbuf(结构cbuf*cbufp,尺寸)
{
结构cbuf*new_cbufp=realloc(cbufp,offsetof(结构cbuf,quoteBuffer)+nNotes*sizeof*cbufp->quoteBuffer);
如果(!new_cbufp)
{
//这里的句柄内存不足。cbufp仍然完好无损,如果不需要,请释放它。
}
返回新的_cbufp;
}
别处作废(作废)
{
结构cbuf*acbuf=NULL;
acbuf=realloc_cbuf(1);
acbuf=realloc_cbuf(10);
//等等。
}
我认为您没有理解为什么有人会将结构的最后一个元素作为单个元素数组。这是一个在旧C代码中使用的技巧,可以使结构大小变长
您可以编写如下代码:
Bitmapset *p = malloc(offsetof(Bitmapset, quoteBuffer) + n * sizeof(quote));
然后编写如下代码:
a->quoteBuffer->time;
a->quoteBuffer[i].time;
p->quoteBuffer[0]
最多:
p->quoteBuffer[n-1]
正如您所猜测的,您不希望直接将指针分配给quoteBuffer
那么,为什么要将quoteBuffer声明为:
引用quoteBuffer[1];
而不是
quote*quoteBuffer;
?
这是因为你不想单独分配quoteBuffer。单个分配可用于整个cbuf,包括内联报价数组。
quoteBuffer[1]
这有什么意义?您不能更改cbuf
结构吗?例如,quoteBuffer
是一个指针,用于初始化cbuf结构中的引号数组。我想我也可以引用quoteBuffer[]。但是我使用了1,因为我以后要用malloc修改大小。最好用一个指向引号的指针,而不是数组。@JoachimPileborg,比如quote*quoteBuffer;在cbuf结构内部?如果我想用一个新的替换当前的quoteBuffer,它会是cbuf->quoteBuffer=newBuffer吗?是的,但别忘了先释放()它,否则会造成泄漏。当然,如果不使用,将其初始化为null总是一个好主意。@Devolus free()首先是原始的quoteBuffer吗?那么自由(cbuf->quoteBuffer)然后cbuf->quoteBuffer=newBuffer?是的。为了安全起见,您应该将其初始化为NULL,在释放之前,您应该执行if(a->buffer)free(a->buffer);a->buffer=malloc(新大小)代码>