Maestro
Maestro

Reputation: 9508

Set array size at runtime

I know how to create a structure array inside a function:

typedef struct item
{
    int test;
};

void func (void) 
{
    int arraysize = 5;
    item ar[arraysize];  
}

But how do I to the same when the array is declared globally:

typedef struct item 
{
    int test; 
};

item ar[];

void func (void)
{
    int arraysize = 5;
    // What to here?
}

Upvotes: 2

Views: 24898

Answers (5)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58251

May be you like this:

typedef struct item 
{
    int test; 
};

item *arr;

void func (void)
{
    int arraysize = 5;
    arr = calloc(arraysize,sizeof(item)); 
     // check if arr!=NULL : allocation fail!
     // do your work 

    free(arr);
}

But its dynamic allocation!

And if arraysize known at compilation time. then better to create a macro like this:

#define arraysize  5

typedef struct item 
{
    int test; 
};

item arr[arraysize];  

side note using upper case for macro constants is good practice

Upvotes: 1

Jack
Jack

Reputation: 16724

You can't modify the size of an array at run time. You can perform a dynamic memory allocation and call realloc() when needed.

EDIT: In your case,I suggest do somethig like this:

item *ar;

    void func(void)
    {
      int arraysize = 5;
      ar = malloc(arsize);
      if(ar) {
      /* do something */
     }
     //don't forget to free(ar) when no longer needed
    }

Upvotes: 0

Jim Rhodes
Jim Rhodes

Reputation: 5085

typedef struct item 
{
    int test; 
};

#define ARRAYSIZE 5

item ar[ARRAYSIZE];

Upvotes: 1

David Grayson
David Grayson

Reputation: 87376

item * ar:
int count;

void foo()
{
    count = 5;
    ar = malloc(sizeof(item) * count);
    // check to make sure it is not null...
}

Upvotes: 2

ouah
ouah

Reputation: 145829

Variable length arrays are only allowed in C for arrays with automatic storage duration. Arrays declared at file scope have static storage duration so cannot be variable length arrays.

You can use malloc to dynamically allocate memory for an array object whose size is unknow at compilation time.

Upvotes: 3

Related Questions