vendredi 28 mars 2014

Find an array element in compile time


Vote count:

0




First of all, sorry if this question (or some similar one) has been previously asked, I've searched for it but I've not found a valid solution in plain C. Also, sorry for the extension.


I've got an array like this:



struct item{
int id;
char *str;
};

const struct item items[] = {
{4, "FIRST_ELEMENT"},
{6, "SECOND ELEMENT"},
{0, NULL}
}


How I could know, in compile time, what position of the array hold the element with id number 4? I could do this in C++ with templates, but in plain C I've no idea how to achieve it.


Please note that the ids of the elements are non-consecutives: I can have all the elements with ids 1-200 and them the ids 4000-4500 filled. I cannot choose the ids.


-- long version --


The elements I manage have inter-dependence. For example, if I process an element with id 10, I've got to process the element with id 15 and 20, all in a predefined way.


At the moment, I've got an struct like this:



#define MAX_NUMS_OF_CHILDS 5

struct item{
int id;
char *str;
int childs_id[MAX_NUM_OF_CHILDS];
struct item *child[MAX_NUM_OF_CHILDS];
};

const struct item items[] = {
{4, "FIRST_ELEMENT"},
{6, "SECOND_ELEMENT"},
{10, "FATHER ELEMENT", {15, 20}}
{15, "SON ELEMENT 1"},
{120, "SON ELEMENT 2"},

{0, NULL}
}


And, at startup time, a function fills the item->child with the information of item->child_id. But I'm sure there is a more elegant way to do this, omitting the child_id field at all.


Thanks in advance!



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire