0

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;
}

3 Answers 3

1

Use array notation - factors[index].

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

Comments

0
static const float[] initials = { .... };
factors = malloc(sizeof(initials));
memmove(factors,initials,sizeof(initials));

2 Comments

I had this thought in mind, but isn't there some more elegant way?
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.
0

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.

3 Comments

sorry, but this wouldn't work. I have different vectors to return for every lookup.
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.
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.

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.