gpt4 book ai didi

C - 在外部函数的指针数组中分配值

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:58 25 4
gpt4 key购买 nike

假设我有以下情况(一些粗略的伪代码):

struct { 
int i;
} x

main(){
x** array = malloc(size of x pointer); // pointer to an array of pointers of type x
int* size = current size of x // (initally 0)
add(array, size);
}

add(x** array, int* size){ // adds one actual element to the array
x** temp = realloc(array, (*size)+1); // increase the array size by one
free(array);
array = temp;

// My question is targeted here
array[*size] = malloc(size of x); // makes a pointer to the value
array[*size]->i = size;
*size++;
}

我的问题是:一旦 add() 完成,存储在数组中的指针的值是否会随着函数调用堆栈一起消失,因为我在 func() 中分配了它们?我担心他们可能会这样做,在这种情况下,我会有更好的方法来做事吗?

最佳答案

不,他们没有。它们一直存在,直到 malloc() 返回的指针被传递给相应的 free() 函数。如果 malloc() 函数的工作方式与自动数组相同,那么它的存在就毫无意义。

编辑:旁注。当@Ancurio 指出它时,您错误地释放了 malloc() 返回的前一个指针后面的内存,该指针当时无效,因为已使用 realloc()在上面。不要那样做。 realloc() 正确地完成了它的工作。)

关于C - 在外部函数的指针数组中分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12995754/

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