This question already has an answer here:
这个问题在这里已有答案:
- Define new function, array, struct etc inside of parameter of function call [duplicate] 3 answers
- 在函数调用参数内部定义新函数,数组,结构等[复制] 3个答案
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?
如果我知道前面的值而不必为了将它传递给函数而创建数组?
1 个解决方案
#1
8
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.
TL; DR函数需要一个(指向)数组作为输入参数,所以你必须传递一个。如果没有数组,你无法调用它。
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
引用C11,章节§6.5.2.5
[In C99
, chapter §6.5.2.5/p4]
[在C99中,章节§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.
也就是说,printArr()和printArray()是不一样的,但我相信这只是你的代码片段中的一个错字。
#1
8
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.
TL; DR函数需要一个(指向)数组作为输入参数,所以你必须传递一个。如果没有数组,你无法调用它。
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
引用C11,章节§6.5.2.5
[In C99
, chapter §6.5.2.5/p4]
[在C99中,章节§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.
也就是说,printArr()和printArray()是不一样的,但我相信这只是你的代码片段中的一个错字。