Search code examples
carraysfunctiondynamicdynamic-arrays

define arraysize using an int value from a function in c


i want to make my array more flexible. My input comes from a file. I get the information of how big my array needs to be from a function.

My Codesample looks like this:

int albumsize = getAlbumnumberFromFile(inputFile);
struct Album Alben[albumsize];

Now I have to following problem ... I can't do something like this. My IDE (Visual Studio 2017) says this Error:

expression must have a constant value

Thanks Alex


Solution

  • Although C standard allows variable-length arrays (VLA) Visual Studio compilers are not fully standard-compliant (relevant Q&A).

    However, I would discourage use of VLA in this situation even if they were supported, because sufficiently large albumsize may lead to undefined behavior.

    A better approach is to allocate memory dynamically, like this:

    struct Album *Alben = malloc(albumsize * sizeof(*Alben));
    ... // Use the allocated memory here. Once you are done, free it.
    free(Alben);
    

    Note that one important difference between Alben-the-pointer and Alben-the-array is what you get from sizeof: array would report the size of its data, while pointer would report the size of the pointer alone. For that reason you need to keep the value of albumsize around - for example, for iterating the array in a loop.