J...S J...S - 1 month ago 4x
C Question

Passing values directly as array to function in C

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?


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 compound literal. Something like

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

should work fine.

To quote C11, chapter §

[In C99, chapter §]

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.