可以在C中返回并释放动态分配的数组吗?
发布时间:2020-12-16 10:35:31 所属栏目:百科 来源:网络整理
导读:是否可以返回并释放动态分配的数组? 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
是否可以返回并释放动态分配的数组?
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 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); 它可能会泄漏内存.如果你必须做嵌套调用(为什么?),那么你需要: int *c; int *a = mycopy((c = mycopy(b,5)),5); 但是写起来会更干净整洁: int *a = mycopy(b,5); int *c = mycopy(b,5); 这样不容易出错,更容易理解,并且使用稍少的字符来启动! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |