views:

100

answers:

3

I have a function that returns an array of different lengths based on a table lookup. I am malloc'ing required memory for it inside the function but then how can I fill the array from its pointer? The compiler is throwing same error for both of my tries (commented lines). Please help!

int lookup(const char *name, float *factors) {
    int length;
    if(!strcmp(name, "foo")) {
        length = 6;
        factors = malloc(length * sizeof(float));
        // *factors = {0, -0.9, -4.9, -8, -7.8, -23.9};
        // factors = {0, -0.9, -4.9, -8, -7.8, -23.9};
    }
    else if(!strcmp(name, "bar"))
    {
        length = 4;
        factors = malloc(length * sizeof(float));
        // *factors = {0, -3, -6, -9};
    }
    // .......................
    // more else if branches
    // .......................
    else    // error: name not found in table
    {
        factors = NULL;
        fprintf(stderr, "name not found in table!!\n");
        return 0;
    }
    return length;
}
A: 

Been a while since I coded straight C, so forgive minor errors, but try

const float[] initialValue = {0, -0.9, -4.9, -8, -7.8, -23.9};
for (int i=0; i<length; i++)
{
    factors[i] = initialValue[i];
}

The basic problem is that you're trying to use the syntax for initializing constants to initialize a dynamic variable.

Eric J.
sorry, but this wouldn't work. I have different vectors to return for every lookup.
Aamir
This code is meant in lieu of the line **// factors = {0, -0.9, -4.9, -8, -7.8, -23.9};**. You still need to malloc the memory. Glad you found a solution that works for you though.
Eric J.
Actually, the "working solution" (I take it you refer to mine) uses the same technique — copying data from static array, just a bit faster. And for both solutions one would need to define one static array per vector.
Michael Krelin - hacker
+1  A: 

Use array notation - factors[index].

swatkat
A: 
static const float[] initials = { .... };
factors = malloc(sizeof(initials));
memmove(factors,initials,sizeof(initials));
Michael Krelin - hacker
I had this thought in mind, but isn't there some more elegant way?
Aamir
Well, it is quite elegant. Another solution would be not to allocate any memory, but just assign `factors = initials`, but, of course, if you're going to modify factors afterwards, that won't work.
Michael Krelin - hacker