Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何打开宏';当宏位于结构数组中时,是否将名称转换为文字字符串?_C_Macros_Preprocessor_X Macros - Fatal编程技术网

C 如何打开宏';当宏位于结构数组中时,是否将名称转换为文字字符串?

C 如何打开宏';当宏位于结构数组中时,是否将名称转换为文字字符串?,c,macros,preprocessor,x-macros,C,Macros,Preprocessor,X Macros,假设我有以下几点 #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); 这显然不起作用,因为它没有扩展。如何解决这

假设我有以下几点

#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);

这显然不起作用,因为它没有扩展。如何解决这个问题?

不确定这是否是您想要的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'

不确定这是否是您想要的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'

你为什么不使用枚举?然后STR宏将按照您的要求工作。您所追求的是“X宏”,有时是连字符的。甚至还有一个主题标签。我怀疑关于X宏的每一个问题都有标记,但它为您提供了一个起点。您为什么不使用枚举?然后STR宏将按照您的要求工作。您所追求的是“X宏”,有时是连字符的。甚至还有一个主题标签。我怀疑关于X宏的每一个问题都有标记,但它为您提供了一个起点。