简体   繁体   中英

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. 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. 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[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:

 #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 . 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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