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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With