Passing values ​​directly as an array for a function in C

I have a function that takes an integer array as an argument and prints it.

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

Is there any way to pass array values ​​like this

 printArray( {3, 4, 5} ); 

if I know the values ​​in front of the hand without creating an array just to pass its function ?

+8
c arrays parameter-passing function-calls
source share
1 answer

TL; DR Functions expect a (pointer to) an array as an input argument, so you must pass it. There is no way to call this without an array.

However, if you want to ask “without creating an additional array variable , this is certainly possible. You can achieve this using something called a composite literal . Something like:

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

should work fine.

Quoting C11 , chapter §6.5.2.5

[In C99 , chapter §6.5.2.5 / p4]

A postfix expression consisting of a type name in brackets followed by a bracket. The list of initializers is a composite literal. It provides an unnamed object whose value is specified in the list of initializers.

However, printArr() and printArray() do not match, but I believe this is just a typo in your snippet.

+8
source share

All Articles