Home > Back-end >  How to create an n sized array in c
How to create an n sized array in c

Time:07-22

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

CodePudding user response:

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;        
}

CodePudding user response:

As the error message says you may not initialize a variable length array in its declaration

int length = 15;

int LuhnsArray[length] = {0};

Note: A variable length array is an array the size of which is not specified with integer constant expression.

From the C Standard (6.7.9 Initialization)

3 The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type

Instead you could write

#include <string.h>

//...

int length = 15;

int LuhnsArray[length];
memset( LuhnsArray, 0, sizeof( LuhnsArray ) ); 

Or instead of calling the function memset you could initialize the array in a loop as for example

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

Also you could allocate the array dynamically as for example

#include <stdlib.h>

//...

int length = 15;
int *LuhnsArray = malloc( length * sizeof( *LuhnsArray ) );
//..

or instead of malloc you could use calloc to zero initialize the array

#include <stdlib.h>

//...

int length = 15;
int *LuhnsArray = calloc( length, sizeof( *LuhnsArray ) );
//..

Pay also attention to that you may not declare a variable length array in a file scope. Variable length arrays must have automatic storage duration.

  • Related