Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在其范围之外使用局部变量_C++_Arrays_Loops - Fatal编程技术网

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

C++ 在其范围之外使用局部变量,c++,arrays,loops,C++,Arrays,Loops,如何在while循环外使用arrj[],因为数组是while循环的局部变量?您可以尝试使用在循环外声明的向量或数组来保存值。 使用Vector,您可以将_推回 或者使用数组,您可以执行以下操作 由于数组是本地数组,如何在while循环之外使用arrj[] 变量到while循环 你的问题本身就有答案。您不能将arrj out端作为第一个for循环,因为它将在离开此范围时从堆栈中删除 为了使用arrj[],需要在while循环之前声明它: 然而,由于它看起来像是按照用户的选择拥有整数数组,我建议您使

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

您可以尝试使用在循环外声明的向量或数组来保存值。 使用Vector,您可以将_推回 或者使用数组,您可以执行以下操作

由于数组是本地数组,如何在while循环之外使用arrj[] 变量到while循环

你的问题本身就有答案。您不能将arrj out端作为第一个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 */
   }

关于你的问题,你不能。数组的作用域仅在第一个for循环内。另一点,C++实际上没有。如果你需要它,就用它代替。
   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 */
   }
   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)
         }*/
      }
   }