Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Passing an array into a function 'on the fly'

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?

like image 269
Gerardo Marset Avatar asked Sep 19 '10 00:09

Gerardo Marset


2 Answers

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.

like image 183
Matthew Flaschen Avatar answered Nov 17 '22 05:11

Matthew Flaschen


You need to declare the type for your compound literal:

foobar = foo((char *[]){"aa", "bb", "cc"});
like image 5
Carl Norum Avatar answered Nov 17 '22 06:11

Carl Norum