每次循环运行时循环都可以创建一个新的不同数组吗?

Ucl*_*dde 1 c arrays loops

我想在C中创建一个循环,每次运行时都会生成一个新的不同数组.可以这样做吗?如果是这样,怎么样?

有点像:

int main()
{
   for(int i = 0; i < 10; i++)
   {
     int arrayi[5] = {0};
   }
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

预期的行为是有10个数组,分别称为array1,array2,array3,array4,array5,array6,array7,array8,array9,array10; 每个元素包含5个元素,每个元素为0.

Fan*_*Fox 5

这取决于你想要做什么.在您的示例中,您将创建10个单独和单独的数组,但可能它们的使用不是那么有用,因为:

for(int i = 0; i < 10; i++)
{
  int arrayi[5] = {0};  // The array is created here.
} // The array goes out of scope and is destroyed here. It can't be used in the next
  // iteration of the for loop.
// You can't use any of the arrays created here.
Run Code Online (Sandbox Code Playgroud)

如果你想在for循环中使用数组,也许这就是你想要的.

也许你想让阵列坚持下去,以便你可以使用它.那你有两个选择:

  1. 制作一个2d数组:

int arr[10][5]; // Use by indexing eg arr[4][1] is the second 
                // element of the fifth array.
// or
int arr[50]; // A flat packed array, usually accessed via 
             // index: row*rowlength + colomn 
Run Code Online (Sandbox Code Playgroud)
  1. 将每个数组定义为单独的命名对象(非常罕见,这是必需的):

int arrForUse[5];
int arrForDifferentUse[7];
...
int arrXXX[15];
Run Code Online (Sandbox Code Playgroud)

如果阵列真正用于不同的事情并且根本不相关,那么这就是你要做的.它们不会被命名arr1,arr2但是......