Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

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 Example
{
    static int[] foo;
    public static void main(String[] args)
    {
        int size = Integer.parseInt(args[0]);
        foo = new int[size]; // This part
    }
}

Pardon my C ignorance. I've been corrupted by java ;)

like image 494
Paul Wicks Avatar asked Mar 15 '09 20:03

Paul Wicks


1 Answers

/* 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 <stdlib.h>
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.

like image 119
dirkgently Avatar answered Oct 06 '22 11:10

dirkgently