[英]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.