gpt4 book ai didi

c - 指针未在 main 中更新

转载 作者:太空宇宙 更新时间:2023-11-04 06:02:58 24 4
gpt4 key购买 nike

我在另一个文件中有一个调用函数 cbuf_update() 的主程序,该函数又调用 cbuf_sizeChange() 以下是让我感到困惑的地方:在 cbuf_update 中,调用 cbuf_sizeChange 正确更新 cb_ptr,但在 main.c 中,它是我在 sizeChange() 中释放 cb1 时的垃圾.我不能让它成为静态的,因为 main 中有可变数量的 cbuf。我该怎么办?我无法更改 cbuf_update() 的签名。

结构定义:

typedef struct cbuf {
unsigned int max;
unsigned int start;
unsigned int end;
unsigned int size;
quote *quotes;
} cbuf;

从 main.c 调用:

cbuf *eur_jpy;
eur_usd = cbuf_init() ;
cbuf_update(eur_jpy, time, rate) ;

其他文件中的相关方法:

cbuf * cbuf_init()
{
//initialize the cbuf with malloc

return cb1;
}

void cbuf_update(cbuf *cb_ptr, double rate)
{
cb_ptr = cbuf_sizeChange(cb_ptr, 2);
}

cbuf *cbuf_sizeChange(cbuf *cb1, double factor)
{
cbuf *cb2;
quote *quotes;
quotes = (quote *)malloc(cb1->max * factor * sizeof(quote));
cb2 = (cbuf *)malloc(sizeof(*quotes) + 4 * sizeof(unsigned int));

//Update quotes here(exluding it)

cb2->size = cb1->size;
cb2->end = cb1->size - 1;
cb2->max = factor * cb1->max;
cb2->start = 0;
free(cb1->quotes);
free(cb1);

cb2->quotes = quotes;

return cb2;
}

最佳答案

这一点看起来不对:

void cbuf_update(cbuf *cb_ptr, double rate)
{
cb_ptr = cbuf_sizeChange(cb_ptr, 2);
}

它修改 cb_ptr,它是您作为第一个参数传递给 cbuf_update() 的任何内容的本地副本。

您可能需要按照以下思路思考:

void cbuf_update(cbuf **cb_ptr, double rate)
{
*cb_ptr = cbuf_sizeChange(*cb_ptr, 2);
}

而不是调用 cbuf_update(something, rate) 调用 cbuf_update(&something, rate)

关于c - 指针未在 main 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15914170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com