2

I have this array of structs in C:

struct Stream_Bufer {
    int size_;
    int capacity_max;
    int p_read;
    int p_write;
    char data_[320000]; 
} stream_buffer_[30];

But if I make int capacity_max = 320000; I will get the error: "data member initializer is not allowed". One way to initialize, that I found, is:

for(int i = 0; i<30;i++){
    stream_buffer_[i].capacity_max = 320000;
}

Any "clean" way to do this?

carduh
  • 529
  • 1
  • 4
  • 13
  • 2
    Is there any reason in your code for `capacity_max` to have a value that would not be not 320000? At first sight, since the `data_` member has a constant size, you probably should use a constant instead. – SirDarius Nov 03 '15 at 10:58
  • To have a value that allow me to control the remaining size of the buffer, when I write in them. @SirDarius – carduh Nov 03 '15 at 11:09
  • Is your for() loop at global scope? (in C, code is not allowed outside a function, even not in initialisers) – joop Nov 03 '15 at 11:31
  • @joop No. It is inside of a function. – carduh Nov 03 '15 at 11:35
  • Did you compile with `-std=c99` (for GCC) ? Otherwise: declare the `i` outside the for() loop; – joop Nov 03 '15 at 11:40
  • 1
    @joop I think you misread the question, OP's code is correct – M.M Nov 03 '15 at 11:55
  • Your solution is the best one. It's also possible to write .... `= { .capacity_max = 320000, .capacity_max = 320000, .capacity_max = 320000, .capacity_max = 320000, ` etc. up to 30 entries but that is tedious – M.M Nov 03 '15 at 11:56

2 Answers2

-2

Works here, even in c89 mode:

void do_init(void)
{
int ii;

for(ii = 0; ii<30;ii++){
    stream_buffer_[ii].capacity_max = 320000;
        }

}

But, if you want to get rid of the duplicated constants, you could use:

struct Stream_Bufer {
    int size_;
    int capacity_max;
    int p_read;
    int p_write;
    char data_[320000];
} stream_buffer_[30];

#define COUNTOF(a) (sizeof(a) / sizeof(a)[0])

void do_init(void) 
{
int ii;

for(ii = 0; ii< COUNTOF(stream_buffer_); ii++){
        stream_buffer_[ii].capacity_max = sizeof stream_buffer_[ii].data_;
        }
}
joop
  • 4,330
  • 1
  • 15
  • 26
-2

For gnu C compiler you can use this way:

   struct data {
     int a;
     int b;
   } data[2] = {{ .b = 1 }, { .b = 2 }};
nintyfan
  • 386
  • 3
  • 16
  • The question is about initializing an array of 30 structs – M.M Nov 03 '15 at 11:57
  • Designated initializers is a feature of C99, GCC provides this feature as a non-standard extension for C90. In other words, unless you are exclusively using C99 compliant compilers, this code is not portable across toolchains. https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html. Also, this method doesn't scale well for an array of structures. – work.bin Nov 03 '15 at 12:02
  • Yes. 30 structure. I suggest to use include preprocesor directive and Python script to generate array of structure of data. – nintyfan Nov 07 '15 at 10:59