Search code examples
arrayscparametersargumentsfunction-call

Is it possible, in C, to write in one line a call to a function that has an array of strings (ie ptr) or int, or ... as parameter?


Let's consider these two functions :

void my_foo1(char ** my_par, int size) {
    for (int i=0; i<size; i++) printf("%s \n",my_par[i]);
}

void my_foo2(int * my_par, int size) {
    for (int i=0; i<size; i++) printf("%d \n",my_par[i]);
}

To call them, variables are declared and initialized. And after, function are called on a second line with these variables.

char * (my_strs[3])={"hello","world","!!!!"};
my_foo1(my_strs,3);

int my_ints[3]={1,2,3};
my_foo2(my_ints,3);

Is it possible to write something like :

my_foox(????,3)

and avoid the variable declaration ?


Solution

  • It seems like what you're looking for is a compound literal:

    my_foo1((char *[]){"hello","world","!!!!"},3);
    my_foo2((int []){1,2,3},3);
    

    Note that such literals have the lifetime of their enclosing scope.