This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

declare a variable with flexible array members (c99)

Hello everyone,

in c99 I can make a struct with a flexible array member at the end. Is it possible to create such a variable at compile time?

e.g:

struct monitoredArray
{
   unsigned int const arrSize;
   unsigned int nUsed;
   uint8_t array[];
};

static struct monitoredArray myArray = {10, 0, [10] /* this won't work... */};

I'd like to use this for a generic kind of initialization (in respect to the array size) so I can use this in different modules without big modification or use of malloc and an init-function. I just want to know how to write that [10] in the example above.

Thanks
Alexander

Parents
  • Use a pointer and have the array either NULL-terminated, or store the number of elements.

    #define NELEM(a) (sizeof(a)/sizeof(a[0]))
    
    elemt_t elements_a[] = {
        {...},
        {...},
        ...
    };
    
    monitor_t my_monitored_info = {
        "a","TCP",10,127,NELEM(elements_a),elements_a
    };
    
    monitor_t my_other_monitored_info = {
        "b","UDP",19,32,NELEM(elements_b),elements_b
    };
    
    ...
    
    process_elements(&my_monitored_info);
    process_elements(&my_other_monitored_info);
    

    All statically allocated during build time.

Reply
  • Use a pointer and have the array either NULL-terminated, or store the number of elements.

    #define NELEM(a) (sizeof(a)/sizeof(a[0]))
    
    elemt_t elements_a[] = {
        {...},
        {...},
        ...
    };
    
    monitor_t my_monitored_info = {
        "a","TCP",10,127,NELEM(elements_a),elements_a
    };
    
    monitor_t my_other_monitored_info = {
        "b","UDP",19,32,NELEM(elements_b),elements_b
    };
    
    ...
    
    process_elements(&my_monitored_info);
    process_elements(&my_other_monitored_info);
    

    All statically allocated during build time.

Children
No data