Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing values directly as array to function in C [duplicate]

I have a function which accepts an integer array as argument and print it.

void printArray(int arr[3])
{
   int i;
   for(i=0; i<3; ++i)
   {
      printf("\n%d", arr[i]);
   }
}

Is there a way to pass the values of the array like this

printArray( {3, 4, 5} );

if I know the values before hand without having to create an array just for the sake of passing it to the function?

like image 631
J...S Avatar asked Sep 19 '16 09:09

J...S


1 Answers

TL;DR The functions expects a (pointer to) an array as input argument, so you have to pass one. There's no way you can call this without an array.

That said, if you meant to ask "without creating an additional array variable", that is certainly possible. You can achieve that using something called a compound literal. Something like:

 printArr( (int []){3, 4, 5} );

should work fine.

To quote C11, chapter §6.5.2.5

[In C99, chapter §6.5.2.5/p4]

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

That said, printArr() and printArray() are not same, but I believe that's just a typo in your snippet.

like image 132
Sourav Ghosh Avatar answered Oct 19 '22 20:10

Sourav Ghosh