”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何通过C ++中的参考传递数组?

如何通过C ++中的参考传递数组?

发布于2025-03-13
浏览:603

How to Pass an Array by Reference in C  ?
在C中传递一个数组,在C中传递一个数组,通过Refere将数组传递允许我们修改传递给函数的原始数组。当我们在数组类型之前使用ampersand(&)符号时,我们会创建对该数组的引用。

考虑以下代码:

void foo(int(int(&myArray)[100])) { } int main() { int a [100]; foo(a); } 在此示例中,FOO函数接受对100个整数数组的引用。 MyArray之后的括号必须表明参数是数组引用,而不是指针。 expression(&myArray)[100]表示“对100个整数数组的引用”。这是声明数组参考的另一种方法。 The following declarations are equivalent:

int (&myArray)[100]

int *myArray
void foo(int (&myArray)[100])
{
}

int main()
{
    int a[100];
    foo(a);
}
int myArray[]

When passing an array by reference, the compiler treats the function parameter as a pointer to the first element in the array.这意味着对函数中数组的任何更改也将反映在原始数组中。

重要的是要注意void foo(int(&myArray)[100] [100])仅接受100个元素的数组。如果我们试图传递与FOO函数不同大小的数组,则会导致编译时错误。
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3