gpt4 book ai didi

c - 如何根据循环索引访问任意变量名

转载 作者:行者123 更新时间:2023-11-30 21:48:30 24 4
gpt4 key购买 nike

我有一些整数变量,我将它们命名为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 { ... } 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
}

关于c - 如何根据循环索引访问任意变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32396522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com