Search code examples
cinitializationdeclarationvariable-length-array

How to create an n sized array in c


I am very new to C but I am having trouble on what seems a very trivial problem. All I am trying to do is create a n sized array, such that at the time of running I don't know its size and can't specify it. The following code works perfectly well.

int main()
{
        
    int LuhnsArray[15] = {0};

    for(int i = 0; i < 15; i++)
    {
        printf("%i ", LuhnsArray[i]);
        printf("\n");
    }
}

However when I try and so something like this:

int main()
{
    
    int length = 15;
    
    int LuhnsArray[length] = {0};

    for(int i = 0; i < length; i++)
    {
        printf("%i ", LuhnsArray[i]);
        printf("\n");
    }
}

Something which I would deem logical (something which I think would work in python for example) it comes up with an error attached. Could someone please point me in the right direction. Any chance of help from a newbie?

enter image description here


Solution

  • The error is quite self-explanatory. Remove the initialization in definition:

    int LuhnsArray[length]; /* = {0}; nope */
    

    Instead, use memset if you want it zeroed out:

    memset(LuhnsArray, 0, sizeof(LuhnsArray));
    

    Note how memset takes byte size, which we can get conveniently for an array (but not for a pointer!) with sizeof operator.


    Or just a for-loop:

    for(int i = 0; i < length; i++)
    {
        LuhnsArray[i] = 0;        
    }