How to access any variable name according to loop index

前端 未结 5 1908

I have some integer variables, I named them n0 to n9. I want to access them using a loop. I tried this code to do that:

int n0 = 0, n1          


        
5条回答
  •  太阳男子
    2021-01-29 17:44

    Since you can't use "real" arrays, lets use some dynamic memory instead (really silly but ...):

    #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... */
        }
        ...
    }
    

    If you really have several variables that you want to access like you say, well save the pointers to them in an array (or like above) and access them that way, but it's still not by name. If you must access them by name well I think you're left with the pre-processor. I don't know of any other proper way to do it.

提交回复
热议问题