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

前端 未结 5 1078
我在风中等你
我在风中等你 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:37

    /* We include the following to get the prototypes for:
     * malloc -- allocates memory on the freestore
     * free   -- releases memory allocated via above
     * atoi   -- convert a C-style string to an integer
     * strtoul -- is strongly suggested though as a replacement
    */
    #include 
    static int *foo;
    int main(int argc, char *argv[]) {
        size_t size = atoi(argv[ 1 ]); /*argv[ 0 ] is the executable's name */
        foo = malloc(size * sizeof *foo); /* create an array of size `size` */
        if (foo) {  /* allocation succeeded */
          /* do something with foo */
          free(foo); /* release the memory */
        }
        return 0;
    }
    

    Caveat:Off the cuff stuff, without any error checking.

提交回复
热议问题