Search code examples
carraysc89

How can I implement an array whose size is not known at compile time in C89?


Sorry, I'm a bit of a newbie to C and was wondering how you could create an array whose size is not known at compile time before the C99 standard was introduced.


Solution

  • It's very easy. For example, if you want to create a variable length 1D int array, do the following. First, declare a pointer to type int:

    int *pInt;
    

    Next, allocate memory for it. You should know how many elements you will need (NUM_INTS):

    pInt = malloc(NUM_INTS * sizeof(*pInt));
    

    Don't forget to free your dynamically allocated array to prevent memory leaks:

    free(pInt);