aretor
aretor

Reputation: 2569

fill an array in C: is it better to create a static local variable or a passing an array by pointer

I am currently writing a simple function in C, which is structured in this way:

int *fillArray(int dim)
{
    static int ar[dim];
    // fill the array ar in some way
    return ar;
}

It is usually said that using the static keyword in local function is discouraged. I was wondering if it was better to do in the classic way:

void fillArray(int *ar, int dim)
{
    // fill the array ar in some way 
}

As a further fact, consider that I later want to wrap the function in Python code, and the Python function should not take parameters.

Upvotes: 1

Views: 478

Answers (3)

Chirag
Chirag

Reputation: 658

int *fillArray(dim)
{
    static int ar[dim];
    // fill the array ar in some way
    return ar;
}

Fill array using static does not makes much sense. Every time this function will be called, this will return same array (same address of the static array). Therefore, multiple calls to fillArray which returns a static variable, may in fact corrupt the previous use of the array. Also, you should ideally never return the address of a variable locally defined.

Also, second fillArray function makes much sense, as it can be actually reused.

Upvotes: 1

chqrlie
chqrlie

Reputation: 144695

Your fillArray function is incorrect: the size of an object with static duration must be known at compile time. Furthermore, asa suggested by user3150716, returning the address of a local object with static storage would return the same array every time, which might not be the intent.

You should use a different approach:

  • write a function to allocate a new array
  • use a different function to initialize an array with its size passed as an argument.

Here is an example:

#include <stdlib.h>

int *fillArray(int *array, size_t size) {
    if (array != NULL) {
        for (size_t i = 0; i < size; i++)
            array[i] = 0;
       }
    }
    return array;
}

int *newArray(size_t size) {
    return fillArray(malloc(size * sizeof(int)), size);
}

void freeArray(int *array) {
    free(array);
}

Note that allocating and initializing the array to 0 can be performed in a single step with calloc(size, sizeof(int)).

Upvotes: 0

aretor
aretor

Reputation: 2569

As suggested by @alk the first solution does not even compile. Thus the second solution is mandatory, at least for VLA.

Upvotes: 0

Related Questions