说我有以下
#define STR(x) #x
#define ONE 1
#define TWO 2
typedef struct
{
int item;
char * name;
}bag_t;
bag_t my_bag[] =
{
{ONE, ""};
{TWO, ""};
}
我想将名称宏添加到name变量中,如下所示:
my_bag[1].name = STR(my_bag[1].item);
这显然不起作用,因为它没有扩展。怎么解决这个问题?
答案 0 :(得分:2)
不确定这是否是您想要的100%,但也许它足够接近:
#define ONE 1
#define TWO 2
typedef struct
{
int item;
const char *name;
}bag_t;
#define BAG_INIT(n) { n, #n }
const bag_t my_bag[] =
{
BAG_INIT(ONE),
BAG_INIT(TWO),
};
int main(void) {
printf("name of %d is '%s'\n", my_bag[0].item, my_bag[0].name);
return 0;
}
打印:
name of 1 is 'ONE'