lddmonster
lddmonster

Reputation: 63

How can I Return an array from a function without using malloc?

I've been struggling with a simple task in C... (It's been a while.) I need to build a function that creates and resets an array of structs without using any memory allocation functions.

I originally designed it with malloc:

typedef struct {
    int ..
    int ..
} Branch;

Branch* createBranchList (int N)
{
    Branch *List;
    Branch reSet = {0}; // a zero'd Branch struct used for the resetting process
    int i;

    if(!(List=(Branch*)malloc(sizeof(Branch)*N))){
        printf("Allocation error");
        return NULL;
    }

    for(i=0; i<N; i++)
        List[i] = reSet;

    return List;
}

Now how can I do this without using memory allocation? Can I return a reference? I don't think so.

Thanks anyone for helping out.

Upvotes: 2

Views: 1614

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

Safe method (1):

Define a struct with an array member, then return that.

e.g.:

struct MyContainer {
    Thing x[42];
};

MyContainer foo(void) {
    MyContainer m;
    m.x[0] = 5;
    m.x[1] = 10;
    ...
    return m;
}

Obviously, this method will not be possible if the array size is not known to the function at compile-time.

Safe method (2):

Have the caller pass in the array as an argument.

e.g.:

foo(Thing *things, int N) {
    thing[0] = 5;
    thing[1] = 10;
    ...
}

Unsafe method:

Declare a static local array, and return a pointer to that.

This "works" because a static array is not deallocated when it goes out of scope. But it's unsafe because the array will be overwritten next time you use the function (particularly bad in a multi-threaded scenario).

This method will also not be possible if the array size is not known to the function at compile-time.

Upvotes: 7

Related Questions