数组的单个元素作为C中的函数参数?

发布于 2025-02-12 06:45:34 字数 470 浏览 1 评论 0原文

假设我有一个函数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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千里故人稀 2025-02-19 06:45:39

只有写出参考文献长期:

foo(arr[0], arr[1]);

Only by writing out the references longhand:

foo(arr[0], arr[1]);
诺曦 2025-02-19 06:45:38

您可以将数组传递到函数,但是这样做会衰减到指针,因此您不知道大小是多少。您需要将大小作为单独的参数传递,然后您的功能可以循环遍历元素。

int foo(int *arr, int len)
{
    int i, sum;
    for(i=0, sum=0; i<len; i++) {
        sum += arr[i];
    }
    return sum;
}

然后,您可以这样称呼它:

int arr[2] = {1, 2};
foo(arr, 2);

或者,假设数组在本地声明:

foo(arr, sizeof(arr)/sizeof(*arr));

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.

int foo(int *arr, int len)
{
    int i, sum;
    for(i=0, sum=0; i<len; i++) {
        sum += arr[i];
    }
    return sum;
}

Then you can call it like this:

int arr[2] = {1, 2};
foo(arr, 2);

Or, assuming the array was declared locally:

foo(arr, sizeof(arr)/sizeof(*arr));
甜是你 2025-02-19 06:45:37

不,这是不可能的。您将必须调用函数foo这样:

int arr[2] = { 1, 2 };
foo( arr[0], arr[1] );

但是,可以重新定义函数foo这样:

int foo( int arr[2] )
{
    return arr[0] + arr[1];
}

现在,您可以调用函数foo <foo < /代码>这样:

int arr[2] = { 1, 2 };
foo( arr );

No, this is not possible. You will have to call the function foo like this:

int arr[2] = { 1, 2 };
foo( arr[0], arr[1] );

However, it is possible to redefine the function foo like this:

int foo( int arr[2] )
{
    return arr[0] + arr[1];
}

Now, you can call the function foo like this:

int arr[2] = { 1, 2 };
foo( arr );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文