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?

7
  • 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. Commented Nov 3, 2015 at 10:58
  • To have a value that allow me to control the remaining size of the buffer, when I write in them. @SirDarius Commented Nov 3, 2015 at 11:09
  • Is your for() loop at global scope? (in C, code is not allowed outside a function, even not in initialisers) Commented Nov 3, 2015 at 11:31
  • @joop No. It is inside of a function. Commented Nov 3, 2015 at 11:35
  • 1
    @joop I think you misread the question, OP's code is correct Commented Nov 3, 2015 at 11:55

2 Answers 2

-2

For gnu C compiler you can use this way:

   struct data {
     int a;
     int b;
   } data[2] = {{ .b = 1 }, { .b = 2 }};
Sign up to request clarification or add additional context in comments.

3 Comments

The question is about initializing an array of 30 structs
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. gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html. Also, this method doesn't scale well for an array of structures.
Yes. 30 structure. I suggest to use include preprocesor directive and Python script to generate array of structure of data.
-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_;
        }
}

1 Comment

Thats my suggestion...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.