【发布时间】:2014-03-28 19:50:10
【问题描述】:
-- 已编辑--
大家好。我有一个元素数组,这些元素在程序的所有执行过程中都不会改变,并且项目在自己的数组中可以有儿子。我必须在处理之前准备好数组。但是,因为我知道数组不会改变,所以我想将它声明为const,并在编译时准备好所有的,所以我可以扔掉整数int son_id[NUM_OF_SONS],prepare_items()函数和数组在我看来,声明会更清晰。
#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]);
}
我有过这样的经历:
static struct item items[] = {
{4, "FIRST ELEMENT"},
{5, "SND ELM"},
{10, "THIRD ELM"},
{15, "FATHER", {&items[1],&items[2]}},
{0, 0 }
};
但是,数组中可能有大约 200 个元素,我需要能够在其中插入或删除元素(在编译时)。所以&items[1],&items[2] 应该是ITEM_ID(5),ITEM_ID(10),某种预处理指令。怎么可能做到这一点?
先谢谢了,很抱歉发了这么长的帖子。
【问题讨论】:
-
项目在数组中的位置在编译时是已知的,因为它们在源代码的初始化列表中的顺序相同。例如,我可以告诉数组元素
0具有 ID 号为 4 的item。请澄清一下,也许有一个您希望喜欢能够编写但不能编写的代码示例t. -
我认为 OP 要求的是一种独立于初始化元素顺序的方式。例如,允许他在索引 1 中插入编号为 5 的项目,将项目 5 向下移动到索引 2 等。我不知道编译时的方式,所以我可以建议的最好的方法是索引数组,初始化为运行时的开始,它索引项目数组。例如,如果索引器将指向示例项目数组的索引 2,则索引 10。 (不存在的索引器将包含 NULL。)
-
请考虑进一步解释您的问题。现在,通过查看上面的部分,在 -- long version -- 行上,我建议这样做
int searchedID = 4; int i = 0; while ( items[i].id != searchedID ) if ( ++i > sizeof items ) { /* doesn't exist */ break; }和i最终将成为包含元素的索引IDsearchedID = 4,但我感觉被问到的东西没这么简单。也许是语言... -
对不起,我会尽量解释清楚。
-
@DoxyLover,我不能这样做,因为 id 可能是,例如,50000。我不能保存一个 50000 长度的数组,其中 99% 的数组是 NULL 元素。跨度>
标签: c metaprogramming