我有一些整数变量,我把它们命名n0为n9.我想使用循环访问它们.我试过这段代码来做到这一点:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是正确的方法,但我不知道如何正确地做到这一点.
简单的回答:相反,声明一个数组int n[10].
高级答案:这里似乎不是这种情况,但是如果您确实需要使用数组项的单个变量名,无论出于何种原因,您可以使用联合:
typedef union
{
struct
{
int n0;
int n1;
int n2;
... // and so on
int n9;
};
int array[10];
} my_array_t;
Run Code Online (Sandbox Code Playgroud)
如果你有一个旧的恐龙编译器,然后用变量名称声明结构,如 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
Run Code Online (Sandbox Code Playgroud)
或者您可以按名称初始化成员:
my_array_t arr =
{
.n0 = 1,
.n1 = 2,
...
};
Run Code Online (Sandbox Code Playgroud)
愚蠢,如何使用上述类型为变量赋值而不使用数组表示法的人工示例:
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
}
Run Code Online (Sandbox Code Playgroud)
正确的方法是声明一个整数数组而不是10个不同的变量:
int n[10];
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用n[0]through 访问10个int变量n[9].