gpt4 book ai didi

c - 可以在 C 中返回和释放动态分配的数组吗?

转载 作者:太空狗 更新时间:2023-10-29 15:13:50 25 4
gpt4 key购买 nike

是否可以同时返回和释放动态分配的数组?

int *mycopy(int *from, int len)
{
int i;
int *to;

to = malloc(len*sizeof(int));

for(i = 0; i < len; ++i) {
to[i] = from[i]
}

return to;

// how do I free the "to" array?
// do i even need to, or does the array only have function scope
// and get deleted when the function exits?
}

或者是

void mycopy(int *from, int *to, int len);

我唯一的选择?

mycopy 函数只是一个简单的示例,但在实际代码中我想嵌套它们,例如调用它

a = mycopy(mycopy(b, 5), 5)

如何在每次调用函数时不分配更多内存的情况下执行此操作?谢谢。

最佳答案

如果您返回数组,调用代码必须负责释放它(函数必须释放它)。如果您不返回数组,函数必须 释放它,但无论如何该函数都毫无意义。因此,该函数不会释放数组。

如果您使用:

void mycopy(int *from, int *to, int len);

调用代码必须进行内存分配。如果您使用:

void mycopy(int *from, int **to, int len);

函数可以进行分配——但它仍然不能释放它。

但初始功能更好:写的很好。你可以这样调用它:

int b[] = { 1, 2, 3, 9, 2 };
int *a = mycopy(b, sizeof(b)/sizeof(b[0]));
...use a...
free(a);

顺便说一句,您无法承受对复制函数的嵌套调用——或者,至少,您无法使用这种方式来实现它:

a = mycopy(mycopy(b, 5), 5);

它会严重泄漏内存。如果您必须进行嵌套调用(为什么?),那么您需要:

int *c;
int *a = mycopy((c = mycopy(b, 5)), 5);

但是这样写会更干净整洁:

int *a = mycopy(b, 5);
int *c = mycopy(b, 5);

这不太容易出错,更容易理解,并且使用更少的字符来启动!

关于c - 可以在 C 中返回和释放动态分配的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945283/

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