-- Edited --
Hi all. I've got an array of elements that will not change in all the execution of the program, and where items can have sons inside the own array. I've got to prepare the array before process it. However, because I know that the array will not change, I would like to declare it as const
, and prepare all of it in compile time, so I could throw away the integers int son_id[NUM_OF_SONS]
, prepare_items()
function and the array declaration will be, in my opinion, clearer.
#include <stdlib.h>
#include <stdio.h>
#define NUM_OF_SONS 5
struct item{
int id;
char *str;
int son_id[NUM_OF_SONS];
const struct item *son[NUM_OF_SONS];
};
const struct item *find_item(int id);
static struct item items[] = {
{4, "FIRST ELEMENT"},
{5, "SECOND ELM"},
{10, "THIRD ELM"},
{15, "FATHER", {5,10}},
{0, 0 }
};
const struct item *find_item(int id){
int i;
for(i=0; items[i].str != NULL; ++i){
if(items[i].id == id) return &items[i];
}
return NULL;
}
void fill_sons(struct item *item){
int i;
for(i=0;i<NUM_OF_SONS;++i){
if(item->son_id[i]!=0)
item->son[i] = find_item(item->son_id[i]);
}
}
void prepare_items(){
int i;
for(i=0;i<sizeof(items)/sizeof(items[0]);++i){
fill_sons(&items[i]);
}
}
void print_sons(const struct item *item);
void print_item(const struct item *item){
printf("The item %d has the text %s.\n",item->id,item->str);
print_sons(item);
}
void print_sons(const struct item *item){
int i;
for(i=0;i<NUM_OF_SONS;++i){
if(NULL!=item->son[i])
print_item(item->son[i]);
}
}
int main(){
prepare_items();
print_item(&items[0]);
print_item(&items[3]);
}
I've though in something like this:
static struct item items[] = {
{4, "FIRST ELEMENT"},
{5, "SND ELM"},
{10, "THIRD ELM"},
{15, "FATHER", {&items[1],&items[2]}},
{0, 0 }
};
However, there could be about 200 elements in the array, and I need to be able to insert or delete elements in the middle of it (in compile time). So &items[1],&items[2]
should be ITEM_ID(5),ITEM_ID(10)
, some kind of preprocessor instruction. How could achieve that?
Thanks in advance, and sorry for the long post.