我有一些整数变量,我将它们命名为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;
}
}
我知道这不是正确的方法,但我不知道如何正确地做到这一点。
答案 0 :(得分:8)
简单回答:改为声明一个数组,int n[10]
。
高级答案:在这里似乎并非如此,但是如果您确实需要使用数组项的单个变量名,无论出于何种原因,您都可以使用联合:
typedef union
{
struct
{
int n0;
int n1;
int n2;
... // and so on
int n9;
};
int array[10];
} my_array_t;
如果您有一个旧的恐龙编译器,则使用变量名称声明结构,例如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
}
答案 1 :(得分:6)
正确的方法是声明一个整数数组而不是10个不同的变量:
int n[10];
现在,您可以使用n[0]
到n[9]
访问10个int变量。
答案 2 :(得分:0)
几乎不可能可以像您想要的那样访问您的变量,而不需要任何数组。
我想到的只是为每个变量考虑10个不同的案例,所以:
int i;
int n0, n2, n3 ... n9;
for(i=0; i<10; i++)
{
switch(i)
{
case 0: n0++; break;
case 1: ...
}
}
答案 3 :(得分:0)
由于你不能使用“真正的”数组,让我们使用一些动态内存(真的很傻但是......):
#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... */
}
...
}
如果你真的有几个你想要访问的变量,那就把它们保存在一个数组中(或者像上面那样)并以这种方式访问它们,但它仍然不是名字。如果您必须通过名称访问它们,我认为您已经留下了预处理器。我不知道有任何其他正确的方法。
答案 4 :(得分:-2)
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;
}
}
试试这个并告诉我