简体   繁体   English

在循环中访问结构变量

[英]Access structure variables in a loop

My requirement is that i create a structure with variables like我的要求是我创建一个带有变量的结构,例如

struct stu{
    char var_01;
    char var_02;
    .
    .
    char var_30;
}stu_t;

and not use an array instead like而不是使用数组代替

char var[30];

With the above requirement established, i can't figure how to access these variables in a loop by concatenating var_ + iterating integer.建立了上述要求后,我无法弄清楚如何通过连接 var_ + 迭代整数在循环中访问这些变量。 I know i cant just concatenate, store in a variable and use that variable to access.我知道我不能只是连接,存储在一个变量中并使用该变量来访问。

Appreciate any help.感谢任何帮助。 Thanks!谢谢!

Variable names have no meaning at run-time in a C program.在 C 程序中,变量名在运行时没有意义。 The names are only for humans, they are removed during compilation.这些名称仅适用于人类,它们在编译期间会被删除。 That's why you can't build variable names and somehow use those.这就是为什么你不能构建变量名称并以某种方式使用它们。

The solution is to use an external array with pointers:解决方案是使用带有指针的外部数组:

stu_t my_stu;
char * vars[30];
vars[0] = &my_stu.var_01;
vars[1] = &my_stu.var_02;
/* ... and so on ... */

Then you can use vars to access into my_stu :然后您可以使用vars访问my_stu

*vars[0] = 'u';
printf("var_01 is '%c'\n", my_stu.var_01);

Of course this isn't very pretty, but that's what you get.当然,这不是很漂亮,但这就是你得到的。

You can use a pointer for that:您可以为此使用指针:

struct stu{
    char var_01;
    char var_02;
    /* ... */
    char var_30;
}stu_t;

char* ptr = &stu_t.var_01;

while(ptr <= &stu_t.var_30)
{
    *ptr = '0';
    printf("Character #%ld = %c \n", ptr - &stu_t.var_01, *ptr);
    ptr++;
}

You can use union but it's rather "ugly" hack and I wouldn't recommend it, but if you really want it... (Still, it requires using arrays somewhere! Union will make structure and array use the same location in memory.) Example:你可以使用 union 但它是相当“丑陋”的 hack,我不推荐它,但如果你真的想要它......(仍然需要在某处使用数组!Union 将使结构和数组使用内存中的相同位置。 ) 例子:

 #include <stdio.h>

 union Test
 {
     struct
     {
         char var_00;
         char var_01;
         char var_02;
         char var_03;
         char var_04;
     };
     char var[5];
 };

 int main()
 {
     union Test t;
     t.var_01 = 'a';
     printf("%c\n", t.var[1]);
     return 0;
 }

It outputs a .它输出a . Anyway, it's better to simply use array.无论如何,最好简单地使用数组。 Your requirement is kind of weird...你的要求有点奇怪...

If your structure only contains chars, you can do this:如果您的结构只包含字符,您可以这样做:

typedef struct stu_s {
    char a;
    char b;
    char c;
} stu_t;

int main()
{
    stu_t my_struct;
    char *ptr = (char *)(&my_struct);

    ptr[0] = 1;
    ptr[1] = 2;
    ptr[2] = 3;

    printf("%hhd %hhd %hhd\n", my_struct.a, my_struct.b, my_struct.c);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM