如何根据循环索引访问任何变量名称

我有一些整数变量,我把它们命名为n0n9 。 我想使用循环访问它们。 我试过这个代码来做到这一点:

 int n0 = 0, n1 = 0, n2 = 0, n3 = 0, n4 = 0; int n5 = 0, n6 = 0, n7 = 0, n8 = 0, n9 = 0; for(i = 0; i < 10; i++){ if(digit == 1){ n[i] = n[i] + 1; } } 

我知道这不是正确的方法,但我不知道如何正确地做到这一点。

简单的回答:改为声明一个数组,如int n[10]


高级答案:这里似乎不是这种情况,但是如果您确实需要使用数组项的单个变量名,无论出于何种原因,您可以使用union:

 typedef union { struct { int n0; int n1; int n2; ... // and so on int n9; }; int array[10]; } my_array_t; 

如果你有一个旧的恐龙编译器,然后使用变量名称声明struct,例如struct { ... } s;


如何在实际的现实世界计划中使用上述类型:

  my_array_t arr = {0}; for(int i=0; i<10; i++) { arr.array[i] = i + 1; } // access array items by name: printf("n0 %d\n", arr.n0); // prints n0 1 printf("n1 %d\n", arr.n1); // prints n1 2 

或者您可以按名称初始化成员:

  my_array_t arr = { .n0 = 1, .n1 = 2, ... }; 

愚蠢的,如何使用上述类型为变量赋值而不使用数组表示法的人工示例:

  my_array_t arr = {0}; // BAD CODE, do not do things like this in the real world: // we can't use int* because that would violate the aliasing rule, therefore: char* dodge_strict_aliasing = (void*)&arr; // ensure no struct padding: static_assert(sizeof(my_array_t) == sizeof(int[10]), "bleh"); for(int i=0; i<10; i++) { *((int*)dodge_strict_aliasing) = i + 1; dodge_strict_aliasing += sizeof(int); } printf("n0 %d\n", arr.n0); // prints n0 1 printf("n1 %d\n", arr.n1); // prints n1 2 for(int i=0; i<10; i++) { printf("%d ",arr.array[i]); // prints 1 2 3 4 5 6 7 8 9 10 } 

正确的方法是声明一个整数数组,而不是10个不同的变量:

 int n[10]; 

现在,您可以使用n[0]n[9]访问10个int变量。

没有任何数组,几乎不可能像你想要的那样访问你的变量。

我想到的只是为每个变量考虑10个独立的案例,因此:

 int i; int n0, n2, n3 ... n9; for(i=0; i<10; i++) { switch(i) { case 0: n0++; break; case 1: ... } } 

既然你不能使用“真正的”数组,那么让我们使用一些动态内存(真的很傻但是……):

 #define NUMVALS 10 int main(int argc, char *argv[]) { int *values, *ptr, i; ptr = values = malloc(sizeof(int) * NUMVALS); for (i = 0; i < NUMVALS; i++) { ptr++ = 0; /* Set the values here or do what you want */ /* Ofc values[i] would work but looks like array access... */ } ... } 

如果你真的有几个你想要访问的变量,那就把它们保存在一个数组中(或者像上面那样)并以这种方式访问​​它们,但它仍然不是名字。 如果你必须通过名字访问它们,我认为你留下了预处理器。 我不知道有任何其他正确的方法。

 int n[10] = {0}; /*or you can initilize like this also , this will make all the elements 0 in array*/ for(i = 0; i < 10; i++){ if(digit == 1){ n[i] = n[i] + 1; } } 

试试这个让我知道