3

I am declaring an array of struct this way :

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 fine.

Now I need to make tab1 and tab2 in one array global_tab and still initialize data this way but so far I haven't been able to do so. I tried dynamic allocation 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 get 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 be able to do initialize global_tab[0] the same way I did with tab1

2
  • Side note: global_tab[0] = something then global_tab[0] = something else means that the first assignment is pretty much useless. It's like doing int i = 5; i = 6;. Commented Jul 25, 2015 at 11:23
  • 1
    IIRC, C initialiser lists are only available for static and auto storage duration? Commented Jul 25, 2015 at 11:25

2 Answers 2

3

C does not provide array aggregate assignment. The curly brace construct is available only in initialization expressions*. If you would like to place specific data into a dynamically allocated block, you could make a static variable with the data, and use memcpy, like this:

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 struct and array aggregates as an extension, but using this feature makes your code non-portable.

Sign up to request clarification or add additional context in comments.

Comments

2

You are confused about initialization and assignment. These operations are different, despite that they both use =:

int m = 42;  // initialization
int n;
n = 42;  // assignment

The code in error is similar:

global_tab[0] = { {"1487" ,0.144}, {"148",2.1}, {"45",0.01}, {"12475847",0.52}, {"46",1.4}, {"0",5} };

This is assignment, you can't use the initialization syntax. The C99 compound literal is perhaps what you want.

1 Comment

If global_tab wasn't dynamically allocated, it could be initialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.