C: Passing an array to an on-the-fly function

I have a function and I want to pass a char * array to it, but I do not want to create a variable just for this, for example:

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

To get around this, I tried this:

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

But that will not work. I also tried this:

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

It compiles with a warning, and if I run the program, it freezes.
I also tried to play with asterisks and ampersands, but I could not get it to work properly.

Is it possible? If so, how?

+5
source share
3 answers

, . , - . NULL .

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

​​ C99.

+16

:

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

A few times enough arguments:

#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 usually prefer the method suggested by Matthew and Karl.

+1
source

All Articles