How to pass arguments in __VA_ARGS to a 2d character array? [closed]

If you are under C99, you can use 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;
}

Notice that __VA_ARGS__ are evaluated twice in order to get the number of elements using sizeof, as an alternative you can send NULL as last parameter (sentinel):

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

Leave a Comment