2

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.

1
  • 2
    In c you can not return a reference because there is no such thing. Commented Apr 6, 2012 at 13:30

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@MarkTolonen: I was leaving that as exercise for the reader, but fair enough!
Thank you, 1st - i cant use malloc cause thats the requierment of the excersize. 2nd- thank you ill probably use the first method and just pre set a fixed size array in the struct or main function.
Does method 1 hold the array on the stack, and pass just the pointer back?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.