aer*_*lve 1 c++ pointers scope
我有一个关于动态数组范围的快速问题,我认为这会导致我正在编写的程序中出现错误.此片段检查函数参数并分支到第一个或第二个,具体取决于用户传递的内容.
但是,当我运行程序时,我收到与范围相关的错误:
error: ‘Array’ was not declared in this scope
除非我对C++的了解失败,否则我知道在分支完成时,条件内创建的变量会超出范围.但是,我动态分配了这些数组,所以我无法理解为什么我不能在程序中稍后操作数组,因为指针应该保留.
//Prepare to store integers
if (flag == 1) {
int *Array;
Array = new int[input.length()];
}
//Prepare to store chars
else if (flag == 2) {
char *Array;
Array = new char[input.length()];
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以对此有所了解吗?
Array以前申报if.并且你不能将不同类型的数组声明为一个变量,所以我认为你应该使用指针.
int *char_array = nullptr;
int *int_array = nullptr;
//Prepare to store integers
if (flag == 1) {
int_array = new int[input.length()];
}
//Prepare to store chars
else if (flag == 2) {
char_array = new char[input.length()];
}
if (char_array)
{
//do something with char_array
}
else if (int_array)
{
//do something with int_array
}
Run Code Online (Sandbox Code Playgroud)
同样作为j_random_hacker点,你可能想要改变你的程序设计以避免很多 if