How to declare the size of an array at runtime in C?

前端 未结 5 1076
我在风中等你
我在风中等你 2021-01-17 17:19

I basically want to the C of equivalent of this (well, just the part with the array, I don\'t need the class and string parsing and all that):

public class E         


        
5条回答
  •  逝去的感伤
    2021-01-17 17:38

    In C, you can do that with this, if you ignore the error checking:

    #include 
    static int *foo;
    
    int main(int argc, char **argv)
    {
         int size = atoi(argv[1]);
         foo = malloc(size * sizeof(*foo));
         ...
    }
    

    If you don't want a global variable and you are using C99, you could do:

    int main(int argc, char **argv)
    {
        int size = atoi(argv[1]);
        int foo[size];
        ...
    }
    

    This uses a VLA - variable length array.

提交回复
热议问题