在其范围之外使用局部变量
Using local variable outside its scope
while(t!=0)
{
for(j=1;j <=3;j++)
{
cin>>size;
int arrj[size];
for(i=0;i<3;i++)
{
cin>>arrj [i];
}
}
}
如何在 whileloop
之外使用arrj[]
,因为数组是 while 循环的局部变量?
如何在
while
循环之外使用 arrj[],因为数组是while 循环的局部变量?
你的问题本身就有答案。您不能将arrj
放在第一个for
循环之外,因为它将在超出此范围时从堆栈中删除。
为了使用arrj[]
,您需要在while
循环之前声明它:
int t = 2, size = 10;
int arrj[size]; // declare before
while(t!=0) // this should be t--, otherwise your while loop will not end
{
/* code */
}
但是,由于看起来每个用户选择都有整数数组,我建议您使用std::vector<>
,通过它可以实现您想要拥有的东西。
int t = 1, size;
std::vector<int> arrj; // declare here
while(t--)
{
for(int j=1;j <=3;j++)
{
std::cin>> size;
// resize the vector size as per user choise
arrj.resize(size);
// now you can fill the vector using a range based for loop
for(int& elements: arrj) std::cin >> elements;
// or simply
/*while(size--)
{
int elements; std::cin >> elements;
arrj.emplace_back(elements)
}*/
}
}
您可以尝试使用在循环外部声明的向量或数组来保存值。 使用矢量,您可以push_back 或者使用数组,您可以在堆上进行动态分配
相关文章:
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- C++中静态方法的局部变量范围
- 离开范围后如何保护局部变量的值?
- 在其范围之外使用局部变量
- 将局部变量保存到全局向量中,为什么离开局部范围后可以得到这些局部变量?
- 尝试声明函数的局部变量,但得到范围错误
- 局部变量超出范围..我认为
- 变量循环范围会导致返回局部变量的地址引用
- C++ 中静态局部变量的范围和生存期
- 从 Outsie it 范围 C++ 访问局部变量
- 在范围内存在不可复制的局部变量时按值捕获
- Lambdas和引用捕获局部变量:在范围之后访问
- 指针可以将局部变量的内存指向其范围之外?
- 是否可以在其范围之外访问局部变量的内存?
- 如何在C++的另一个范围内使用局部变量
- 在类范围内声明与类属性同名的局部变量