gpt4 book ai didi

c++ - 通过指针调整数组大小

转载 作者:行者123 更新时间:2023-11-30 03:15:39 25 4
gpt4 key购买 nike

我正在方法内调整数组大小,但由于我使用的是指针,内存地址现在不正确。 diffDataTot 指针最初是在 main() 中创建的,然后传递给 calculateField() 方法。 calculateField() 方法包含需要添加到diffDataTot 的新信息,并且需要删除一些旧信息。我使用 resize() 方法调用指出了这一点。

void calculateField(diffData* diffDataTot){
diffData* filler = (diffData*)malloc(newSize * sizeof(diffData));
filler = resize(newSize, diffDataTot);
free(diffDataTot);
diffDataTot = filler;
free(filler);
}

int main{
diffData* diffDataTot = (diffData*)malloc(sizeof(diffData));
calculateField(diffDataTot);
}

我不得不对其进行缩写,因为它来自数千行的全尺寸模拟。但是,问题在于 diffDataTotcalculateField() 方法内部包含本地的正确信息。但是指针指向内存中与 main() 中不同的地址。我可以尝试不使用指针,但我想避免每次调用 calculateField() 时都复制整个数组,因为它非常大。

有什么方法可以让我从 calculateField() 方法传回数组中第一个元素的内存?

最佳答案

您需要传递指针的地址(指针上的指针)。

void
resizing_func(int **elements,
int *elem_count)
{
//---- get rid of additional indirection ----
int *p=*elements;
int count=*elem_count;
//---- work with local variables ----
// ...
int new_count=2*count; // whatever is needed for the problem
p=realloc(p, new_count*sizeof(int));
// ...
//---- make changes visible in calling context ----
*elements=p;
*elem_count=new_count;
}

void
testing_func(void)
{
int count=100;
int *elements=malloc(count*sizeof(int));
// populate elements
resizing_func(&elements, &count);
// use updated elements and count
}

根据问题,realloc() 可以替换为:

  • 分配第二个缓冲区,
  • 使用第一个和第二个缓冲区,
  • 释放第一个缓冲区并继续第二个缓冲区,

如 OP 的问题。
(顺便说一句,请注意 free(filler) 将释放本应保留在 diffDataTot 中的内容)

注意:由于问题被标记为 c++,使用 std::vector 并通过(非常量)引用传递它可能会更好;但提供的源代码看起来像 c

关于c++ - 通过指针调整数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877335/

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