2

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 ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • 1
    Are you aiming to _change_ the values in the arrays in your functions? If not, make them `const char/int **` – Ted Lyngmo Feb 13 '23 at 16:05

2 Answers2

10

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 2
    Note however that this approach does not enforce consistency between the array length and the `size` function argument, whereas this would: `char *my_strs[] = { "hello", "world", "!!!!" }; my_foo1(my_strs, sizeof(my_strs) / sizeof(*my_strs));` – chqrlie Feb 13 '23 at 16:17
2

You can use compound literals as for example

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

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

In the call of the function foo2 the compound literal having the type int[3] is implicitly converted to a pointer of the type int * to its first element.

Pay attention to as the function does not change the passed array then it will be better to declare it like

void my_foo2( const int * my_par, int size) {
    for (int i=0; i<size; i++) printf("%d \n",my_par[i]);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335