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

时间:2018-06-06 04:24:26

标签: c++ arrays loops

while(t!=0)
{
    for(j=1;j <=3;j++)
    {
       cin>>size;
       int arrj[size];

       for(i=0;i<3;i++)
       {
           cin>>arrj [i];
       }
    }
}

如何在while arrj[]之外使用loop,因为数组是while循环的局部变量?

2 个答案:

答案 0 :(得分:1)

  

如何在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)
         }*/
      }
   }

答案 1 :(得分:0)

您可以尝试使用在循环外声明的向量或数组来保存该值。 使用Vector你可以push_back 或者使用数组,您可以 dynamic allocation on heap