8

I have a function, and I want to pass an array of char* to it, but I don't want to create a variable just for doing that, like this:

char *bar[]={"aa","bb","cc"};
foobar=foo(bar);

To get around that, I tried this:

foobar=foo({"aa","bb","cc"});

But it doesn't work. I also tried this:

foobar=foo("aa\0bb\0cc");

It compiles with a warning and if I execute the program, it freezes.
I tried playing a bit with asterisks and ampersands too but I couldn't get it to work properly.

Is it even possible? If so, how?

Gerardo Marset
  • 803
  • 1
  • 10
  • 23

3 Answers3

19

Yes, you can use a compound literal. Note that you will need to provide some way for the function to know the length of the array. One is to have a NULL at the end.

foo((char *[]){"aa","bb","cc",NULL});

This feature was added in C99.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
6

You need to declare the type for your compound literal:

foobar = foo((char *[]){"aa", "bb", "cc"});
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

Some times variable arguments are sufficient:

#include <stdarg.h>
#include <stdio.h>

void func(int n, ...)
{
  va_list args;
  va_start(args, n);
  while (n--)
  {
    const char *e = va_arg(args, const char *);
    printf("%s\n", e);
  }
  va_end(args);
}

int main()
{
  func(3, "A", "B", "C");
  return 0;
}

But I generally prefer the method suggested by Matthew and Carl.

Matthew
  • 47,584
  • 11
  • 86
  • 98