Initialize a global array of arrays of structures
I am declaring an array of structure like this:
struct struct_name tab1[6] ={ {"1487" ,0.144}, {"148",2.1}, {"45",0.01}, {"12475847",0.52}, {"46",1.4}, {"0",5} };
struct struct_name tab2[7] = { {"1" ,0.9}, {"76",5.1},{"46",0.17},{"4625",0.0},{"46252",1.57},{"12",1.5},{"5",1.2} };
This works great.
Now I need to do tab1
both tab2
in the same array global_tab
and still initialize the data that way, but until now I couldn't do it. I have tried dynamic placement like this
global_tab = malloc(2 * sizeof(struct struct_name *));
global_tab[0] = malloc(100 * sizeof(struct struct_name));
global_tab[0] = { {"1487" ,0.144}, {"148",2.1}, {"45",0.01}, {"12475847",0.52}, {"46",1.4}, {"0",5} };
But I am getting this error
error: expected expression before ‘{’ token
global_tab[0] ={ {"1487" ,0.144}, {"148",2.1}, {"45",0.01}, {"12475847",0.52}, {"46",1.4}, {"0",5} };
I want to do initialization the global_tab[0]
same as I did withtab1
source to share
C does not enforce an array aggregate assignment. The curly brace construction is available only in * initialization expressions . If you want to put certain data in a dynamically allocated block, you can make a variable static
with the data and use memcpy
, for example:
static struct struct_name tmp0[] ={ {"1487" ,0.144}, {"148",2.1}, {"45",0.01}, {"12475847",0.52}, {"46",1.4}, {"0",5} };
global_tab[0] = malloc(sizeof(tmp0));
memcpy(tmp0, global_tab[0], sizeof(tmp0));
* Some compilers provide structure and array aggregates as an extension, but using this function makes your code not portable.
source to share
You are confused about initialization and assignment . These operations are different even though they both use =
:
int m = 42; // initialization
int n;
n = 42; // assignment
The error code is similar:
global_tab[0] = { {"1487" ,0.144}, {"148",2.1}, {"45",0.01}, {"12475847",0.52}, {"46",1.4}, {"0",5} };
This is the assignment, you cannot use the initialization syntax. C99 compound literal is what you want.
source to share