在其范围之外使用局部变量

Using local variable outside its scope

本文关键字:局部变量 范围      更新时间:2023-10-16
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 或者使用数组,您可以在堆上进行动态分配