Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array of structs with a string - manipulation/access

Tags:

c

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?

like image 405
jetru Avatar asked Dec 21 '10 19:12

jetru


1 Answers

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.

like image 57
icecrime Avatar answered Nov 15 '22 05:11

icecrime