Reputation: 1993
I have an array that looks like this:
struct table_elt
{
int id;
char name[];
}
struct table_elt map[] =
{
{123,"elementt1"},
{234,"elt2"},
{345,"elt3"}
};
I'm trying to access these elements through map[1].name, etc. However, it doesn't seem to be able to fetch the elements correctly, and I get random junk. I think this is because the compiler doesn't know where the elements will land up due to varying. What's the best way to fix this, while still maintaining as much flexibility and simplicity?
Upvotes: 5
Views: 810
Reputation: 1022
You cannot have an array of undefined length inside the table_elt structure. You can change it to a char * and have it point at a char array allocated elsewhere, or pick an appropriate length for your array and include it in the struct definition:
struct table_elt
{
int id;
char name[15];
}
Upvotes: 1
Reputation: 76835
You probably want :
struct table_elt
{
int id;
const char *name;
}
struct table_elt map[] =
{
{123,"elementt1"},
{234,"elt2"},
{345,"elt3"}
};
On a side note, table_elt
doesn't even need a name if it's used in this context only.
Upvotes: 8