gpt4 book ai didi

c - 如何将 __VA_ARGS 中的参数传递给二维字符数组?

转载 作者:行者123 更新时间:2023-11-30 21:35:22 25 4
gpt4 key购买 nike

我需要从 __VA_ARGS 获取结果到函数,然后我需要将每个参数的字符串传递给二维字符数组。

最佳答案

如果你在C99下,可以使用compound literals

#include <stdio.h>

#define MACRO(...) func( \
sizeof((char *[]){__VA_ARGS__}) / sizeof(char *), \
(char *[]){__VA_ARGS__} \
)

void func(size_t n, char **p)
{
size_t i;

for (i = 0; i < n; i++) {
printf("%s\n", p[i]);
}
}

int main(void)
{
MACRO("abc", "def", "ghi");
return 0;
}

请注意,__VA_ARGS__ 被评估两次,以便使用 sizeof 获取元素数量,作为替代方案,您可以在最后发送 NULL参数(哨兵):

#include <stdio.h>

#define macro(...) func((char *[]){__VA_ARGS__, NULL})

void func(char **p)
{
while (*p != NULL) {
printf("%s\n", *p);
p++;
}
}

int main(void)
{
macro("abc", "def", "ghi");
return 0;
}

关于c - 如何将 __VA_ARGS 中的参数传递给二维字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35621786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com