0

When I initialize a single element into a void structure, it works fine:

void* CMD_ARRAY[] = 
{
  {"+++\r"},
  {"+++\r"},
  {"+++\r"},
};

However, when I try to add more elements to the structure, i.e.:

void* CMD_ARRAY[] = 
{
  {"+++\r" ,  4,  1300},
  {"+++\r" ,  4,  1300},
  {"+++\r" ,  4,  1300},
};

This results in an error:

expected a "}"

What is the difference between a single element as in the 1st example, and a structure of a structures (which are also considered as elements)?

How can I achieve initialization of this void structure with mixed types?

Update: So I understand that the compiler doesn't know how to handle different types in the same elements. Is there a way to define these types on the fly (i.e. using casting) without actually defining the structure outside this definition (i.e. using an array of strucutres)?

4

3 回答 3

0

The use of curly brackets as initializer implies the initialization of a structured information. You are initializing a void-pointer array. So the compiler expects a set of pointers he can store in this array. Your second variant is not a pointer anymore it's a approximately 12 bytes long. There is not enough room for this in a single void-pointer array cell.

Moreover I get the feeling that something bad is rising at the horizon while looking at this code. What exactly are you trying to do?

于 2013-01-27T09:11:17.937 回答
0

You have an array of pointers not an array of structures. A literal string initialiser is a single pointer that can be assigned to a void pointer, to use a structured initialiser, it has to be assigned to a matching structure - otherwise how would the compiler know whet to place the data in memory?

于 2013-01-27T09:12:52.257 回答
0

I would suggest that the compiler can't guess certain details regarding your implicit struct declarations. For example, how is your compiler to guess that I wanted y in the example below to be a short?

struct foo { char *x; short y; unsigned int z; };

void* CMD_ARRAY[] = 
{
  &(struct foo){"+++\r" ,  4,  1300},
  &(struct foo){"+++\r" ,  4,  1300},
  &(struct foo){"+++\r" ,  4,  1300},
};

This could be expanded at the cost of legibility to:

void* CMD_ARRAY[] = 
{
  &(struct { char *x; short y; unsigned int z; }){"+++\r" ,  4,  1300},
  &(struct { char *x; short y; unsigned int z; }){"+++\r" ,  4,  1300},
  &(struct { char *x; short y; unsigned int z; }){"+++\r" ,  4,  1300},
};

edit: In addition to the cost of legibility, consider what will happen if you decide to change your struct at the higher level. You'll have to do plenty of finding/replacing in the lower level. Does this sound sweet to you?

于 2013-01-27T10:00:21.000 回答