Reputation: 1047
I cannot get designated initialiser syntax working when using a range. I know that designated initialisers are possible with arrays, and I want to initialize a struct array so that all members are the same at boot.
EDIT: error is
error: array index range in initializer exceeds array bounds 32 |
[0 ... NODELIST_LEN].dev_status = DW_DEV_DISABLED
typedef struct {
int dev_status;
}DW_data;
typedef struct{
DW_data list[NODELIST_LEN];
}DW_nodelist;
I have tried the following:
DW_nodelist dw_list = {
.list[0 ... NODELIST_LEN].dev_status = DW_DEV_DISABLED
}
DW_nodelist dw_list = {
.list = {
[0 ... NODELIST_LEN].dev_status = DW_DEV_DISABLED
}
}
I even gave these a whirl just for laughs:
DW_nodelist dw_list = {
.list = {
.dev_status[0 ... NODELIST_LEN] = DW_DEV_DISABLED
}
}
DW_nodelist dw_list = {
.list = [0 ... NODELIST_LEN].dev_status = DW_DEV_DISABLED
}
What am I doing wrong, is this even possible with a struct array?
Upvotes: 1
Views: 540
Reputation: 214310
In case someone wonders how to do the same with pure standard C language, it is a bit trickier. Given this:
#define DW_DEV_DISABLED 666
#define NODELIST_LEN 32
typedef int DW_data;
typedef struct{
DW_data list[NODELIST_LEN];
}DW_nodelist;
We could cook up a macro for array initialization like this:
DW_nodelist dw_list =
{
.list = { INIT(NODELIST_LEN, DW_DEV_DISABLED) }
};
Where the first argument to the macro is the number of items to initialize and the second is the value. So here we want to set 32 items to some non-zero value. It is possible in standard C, but we need to declare a lot of macros like these:
#define INIT_1(val) val
#define INIT_2(val) INIT_1(val), INIT_1(val)
#define INIT_4(val) INIT_2(val), INIT_2(val)
#define INIT_10(val) INIT_4(val), INIT_4(val), INIT_2(val)
#define INIT_32(val) INIT_10(val), INIT_10(val), INIT_10(val), INIT_2(val)
And then we can call these with another macro to make it all somewhat variable:
#define PREPROC(n, val) INIT_##n(val)
#define INIT(n, val) PREPROC(n, val)
Upvotes: 1
Reputation: 26800
You are exceeding array bounds with 0 ... NODELIST_LEN
. You have to stop at NODELIST_LEN - 1
.
The below will work:
DW_nodelist dw_list = {
.list[0 ... NODELIST_LEN-1].dev_status = DW_DEV_DISABLED
};
Note that the usage of ...
(specifying a range of elements) is a GCC-specific extension not supported by standard C.
The GCC compiler warns if you use the -Wpedantic
option.
warning: ISO C forbids specifying range of elements to initialize [-Wpedantic] 13 | .list[0 ... NODELIST_LEN-1].dev_status = DW_DEV_DISABLED
Upvotes: 1