2

I'm having trouble with a certain "program flow" that I'm trying to implement.

The output in the following MWE is supposed to say "Sum: 10" but it says "Sum: 0" because the function set_array_element does not set array elements. Why doesn't it?

#include <stdio.h>
#include <stdlib.h>

typedef struct example example;
struct example {
    int nrOf;
    double a[];
};

void initialize_example_array(example *e);
void set_array_element(double *el);

example new_example(int nrOf)
{
    example *e = malloc(sizeof(example) + nrOf*sizeof(double));
    e->nrOf = nrOf;
    initialize_example_array(e);
    return *e;
}

void initialize_example_array(example *e)
{
    printf("%d\n", e->nrOf);
    for(int i=0; i<e->nrOf; i++)
    {
        set_array_element(&e->a[i]);
    }
}

void set_array_element(double *el)
{
    *el = 1;
}

int main(int argc, const char * argv[]) {
    example e = new_example(10);

    printf("%d\n", e.nrOf);

    int i, s=0;
    for(i=0; i<e.nrOf; i++)
    {
        printf("%f\n", e.a[i]);
        s+= e.a[i];
    }
    printf("Sum: %d\n", s);

    return 0;
}

1 Answer 1

4

The flexible array member, this is the member a of struct example, is not a pointer. It's address is calculated using the address of the struct.

A struct with a flexible array member cannot be assigned using the simple assignment operator, like it is done in your example:

example e = new_example(10);

where the function returns:

return *e;

You will have to return the pointer:

example* new_example(int nrOf)
{
    example *e = malloc(sizeof(example) + nrOf*sizeof(double));
    e->nrOf = nrOf;
    initialize_example_array(e);
    return e;
}

example* e = new_example(10);
printf("%d\n", e->nrOf);
...
Sign up to request clarification or add additional context in comments.

1 Comment

In other words: An array is not a pointer! Every C teacher should make this clear with the very first sentence when it comes to arrays!

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.