【问题标题】:Using local variable outside its scope在其范围之外使用局部变量
【发布时间】:2018-06-06 04:24:25
【问题描述】:
while(t!=0)
{
    for(j=1;j <=3;j++)
    {
       cin>>size;
       int arrj[size];

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

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

【问题讨论】:

  • 关于你的问题,你不能。数组的范围仅在第一个 for 循环内。还有一点,C++ 实际上没有variable-length arrays。如果需要,请改用std::vector

标签: c++ arrays loops


【解决方案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&lt;&gt;,通过它你可以实现你想要的。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 2016-04-19
      相关资源
      最近更新 更多