C 如何通过将标记粘贴在一起来创建类似宏标记的函数

C 如何通过将标记粘贴在一起来创建类似宏标记的函数,c,macros,c-preprocessor,C,Macros,C Preprocessor,我有一组预定义的宏(我无法更改),其中每个宏都将数组的索引作为输入。我想创建另一个宏,以便能够通过将标记粘贴在一起来选择要使用的先前定义的宏 我尝试创建一个包含两个参数的宏:x,它选择以前定义的要使用的宏;和ind,它被传递到所选宏 下面的代码是使用 因此,在我将其放入一个相当大的应用程序之前,我可以找出基本代码 #include <stdio.h> //struct creation struct mystruct { int x; int y; }; //cr

我有一组预定义的宏(我无法更改),其中每个宏都将数组的索引作为输入。我想创建另一个宏,以便能够通过将标记粘贴在一起来选择要使用的先前定义的宏

我尝试创建一个包含两个参数的宏:
x
,它选择以前定义的要使用的宏;和
ind
,它被传递到所选宏

下面的代码是使用 因此,在我将其放入一个相当大的应用程序之前,我可以找出基本代码

#include <stdio.h>

//struct creation
struct mystruct {
    int x;
    int y;
};

//create array of structs
struct mystruct sArr1[2] = {{1,2},{3,4}};
struct mystruct sArr2[2] = {{5,6},{7,8}};

//define macros
#define MAC1(ind) (sArr1[ind].x)
#define MAC2(ind) (sArr2[ind].y)

// Cannot change anything above this //

//my attempt at 2 input macro
#define MYARR(x,ind) MAC ## x ## (ind)

int main() {
    printf("%d\n", MYARR(1, 0));
    return 0;
}
第29行应为:

#define MYARR(x,ind) MAC##x(ind)

我测试过了。它打印了您想要的“1”。

首先,标记粘贴创建一个标记。如果仔细阅读错误消息,您会发现它正确地将
MAC
1
粘贴在一起,问题是用
(of
(ind)
)粘贴
MAC1
)。您真的应该有一个令牌(即一个预处理器符号)
MAC1吗(
?但是请注意,
MYARR
的所有实例中的第一个参数必须是显式常量
1
2
,而不是具有此值的更复杂的表达式。非常简单的解决方案。我想我可能无法完全理解它。谢谢!
#define MYARR(x,ind) MAC##x(ind)