-2

I have a structure like this:

typedef struct {
    float batch;
    float length;
    uint32_t test;
    char val[0];
}
PARAM;

And am calling a function with this format:

void fillValues(float val, float len, uint32_t tmp, const void* prw);

I declare the structure and allocate some memory:

PARAM *first = calloc(10, sizeof(PARAM));

The problem I am having is if I print the values of first->data before calling the function, it contains as expected but if I call the function:

fillValues (test, first->batch, first->length, first->test, &first->val);

and try and print prw inside, it contains nothing.

I think I am passing the value incorrectly because it is declared as a char array but the function parameter is a const void *. P.S. I don't want to change the fucntion param type.

The only part where prw is used in fillValues is converting to a double:

double *value
value = (double*)first->data;
*value = *(const double*)pwr;
homeGrown
  • 375
  • 1
  • 8
  • 25

1 Answers1

3

char val[0]; is nonsense, this is not valid C. Arrays cannot have size zero. The GCC compiler had a non-standard language extension that allowed this (as a 1990s fix to the old "struct hack"). This all turned obsolete in the year 1999 with the C99 standard, when flexible array members were added to the language.

Change your struct to this:

typedef struct {
    float batch;
    float length;
    uint32_t test;
    char val []; // flexible array member
}
PARAM;

Then allocate memory as

PARAM* p = malloc(sizeof(PARAM) + sizeof(n));

where n is the length you want the array char val[] to have.


Since your function has the format const void* prw, the last parameter in the call should be first->val and not &first->val.

This is a perfect example of why void pointers should be avoided when possible: they tend to hide bugs and block compiler warnings.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396