c++ - 在递归/另一个函数中返回静态/普通数组

标签 c++ c arrays recursion vector

在一个函数中声明一个非静态数组,它被返回并存储在 main 中的另一个非静态数组中。

Q 1> 我知道当传递一个数组时,它是通过指针传递的(而不是通过引用),因此传递函数中对数组所做的任何更改都会反射(reflect)在原始函数中,但在本例中是在返回该数组时对另一个函数说 main 当原始数组超出其函数范围时不应该被销毁吗?

Static variable retain value within function calls and it's lifetime is the entire program so it is justified for a static array but why so for a non static array?

Q 2>现在假设我们在一个进行递归的函数内声明了一个非静态数组,该数组是否在每次递归时都被声明?它没有超出范围,因此数组被重新声明,那么为什么它不给出重新声明错误呢?它是一个新数组还是该数组被覆盖?

假设我们现在有一个静态数组,它是一个静态数组,它只声明一次..

Does changes made in the array in one recursion gets reflected in another recursion if the array is static/non static?

我尝试了一下,发现对于非静态数组,更改不会得到反射(reflect),但在静态数组中,更改会得到反射(reflect),所以它基本上归结为第一个问题?

Q 3> 假设我们声明了一个静态数组,然后运行两个测试(需要提到的一个重要问题是我们需要在下一个递归中使用上一个递归中获得的值),数组值存储在第一个测试用例中(它是静态的)导致在第二次测试用例运行期间存储不正确的值(我们将其视为 vector ,因此当我们在第二次运行中推送元素时,它会给出不正确的输出,因为第一次运行中存储的值已经在 vector 中) 。您能否建议一种无需删除静态数组即可解决此问题的方法

I know I have asked many questions all together at the same time, but I did that because they are all related 1 and 2 more so. 3 will help me clear my doubts better. It will be very helpful if you can clear the doubts. Thank You

最佳答案

Q 1> I know that when an array is passed, it is passed by pointer(not by reference) so any changes made to the array in the passed function gets reflected in the original function but in this case while returning that array to another function say main shouldn't the original array be destroyed when it goes out of it's function scope?

是的,当它声明的函数退出时,数组将被销毁。如果您在此之后继续尝试使用它,您将得到“未定义的行为” - 这意味着任何事情都可能发生。它可能看起来有效,也可能崩溃,或者可能包含垃圾数据。

Q 2>Now say we have a non-static array declared inside a function that undergoes recursion, does the array gets declared each time it recurses? It doesn't goes out of the scope so the array is re-declared so why doesn't it gives a redeclaration error? Is it a new array or does the array gets over-written?

这是一个新数组。对函数的每次调用都会获得该函数的局部变量的自己的拷贝。

Q 3> Say we declared a static array and we run two tests(one imp thing to mention is we need the values we get in the previous recursion for the next recursion), the arrays values stored in the first test case(it being static) leads to incorrect values stored during the second test case run(well consider it as a vector so it will give incorrect output when we push the elements in second run since the values stored in the first run are already in the vector). Can you suggest a way to get around this w/o removing the static array

您可以将其设置为全局,然后在测试之间清除它。这不是最漂亮的解决方案,但可能是最简单的。

关于c++ - 在递归/另一个函数中返回静态/普通数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879294/

相关文章:

c - 从文件 C 中读取数字列表

c++ - 图像在 OSG 中随着旋转而消失

c++ - 如何初始化 std::array<std::array<T, 2>, 2> 的对象?

c - C 读取字符串中的字符数

c - 如何在 C 中的同一结构中使用两个可变长度数组

c - 通用快速排序不起作用

c++ - 如何在 C/C++ 中使用 lame 将 mp3 解码为 wav?

c++ - 使用和不使用 std=c++0x 混合库的任何问题

javascript - 使用泛型方法访问对象值

c# - 获得围绕给定值的随机偏差