C. E. C. E. - 2 months ago 10
C Question

Trouble assigning value of array element via pointers

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

Answer

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);
...
Comments