数组的单个元素作为C中的函数参数?
假设我有一个函数foo
:
int foo(int a, int b)
{
return a + b;
}
我可以以任何方式调用foo
带有数组,并且数组的每个元素都作为一个参数?
例如:
int arr[2] = {1, 2};
foo(arr); // Should return 3
在JavaScript中,我可以做:
let arr = [1, 2];
foo(...arr); // Returns 3
C中有类似的东西吗?
Suppose I have a function foo
:
int foo(int a, int b)
{
return a + b;
}
Can I in any way call foo
with an array and have each elements of the array act as one parameter?
e.g:
int arr[2] = {1, 2};
foo(arr); // Should return 3
In JavaScript I can do:
let arr = [1, 2];
foo(...arr); // Returns 3
Is there anything similar in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只有写出参考文献长期:
Only by writing out the references longhand:
您可以将数组传递到函数,但是这样做会衰减到指针,因此您不知道大小是多少。您需要将大小作为单独的参数传递,然后您的功能可以循环遍历元素。
然后,您可以这样称呼它:
或者,假设数组在本地声明:
You can pass an array to a function, but in doing so it decays to a pointer so you don't know what the size is. You would need to pass the size as a separate parameter, then your function can loop through the elements.
Then you can call it like this:
Or, assuming the array was declared locally:
不,这是不可能的。您将必须调用函数
foo
这样:但是,可以重新定义函数
foo
这样:现在,您可以调用函数
foo <
foo < /代码>这样:
No, this is not possible. You will have to call the function
foo
like this:However, it is possible to redefine the function
foo
like this:Now, you can call the function
foo
like this: