将数组传递给C ++中的函数(Passing Arrays to Function in C++)

系统教程 行业动态 更新时间:2024-06-14 17:04:03
将数组传递给C ++中的函数(Passing Arrays to Function in C++) #include <iostream> using namespace std; void printarray (int arg[], int length) { for (int n = 0; n < length; n++) { cout << arg[n] << " "; cout << "\n"; } } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray(firstarray, 3); printarray(secondarray, 5); return 0; }

这段代码可以工作,但是我想了解数组是如何传递的。

当从main函数调用printarray函数时,数组的名称将被传递。 数组的名称指的是数组的第一个元素的地址。 这等于int arg[]吗?

#include <iostream> using namespace std; void printarray (int arg[], int length) { for (int n = 0; n < length; n++) { cout << arg[n] << " "; cout << "\n"; } } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray(firstarray, 3); printarray(secondarray, 5); return 0; }

This code works, but I want to understand how is the array being passed.

When a call is made to the printarray function from the main function, the name of the array is being passed. The name of the array refers to the address of the first element of the array. How does this equate to int arg[]?

最满意答案

语法

int[]

int[X] // Where X is a compile-time positive integer

完全一样

int*

当在函数参数列表中(我省略了可选名称)。

另外,一个数组名称在传递给一个函数(并没有被引用传递时)衰减到指向第一个元素的指针,所以int firstarray[3]和int secondarray[5]衰减为int* s。

当使用相同的索引时,数组解引用和下标语法的指针取消引用(下标语法为x[y] )也会产生相同元素的左值。

这三个规则相结合,使代码合法化,并且可以预期如何运作; 它只是将指针传递给函数,以及数组的长度,这些数组在数组衰减到指针之后就不可能知道。

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

Are exactly the same as

int*

When in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

更多推荐

本文发布于:2023-04-24 21:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/92771f51aff98055480cf5772db22218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   函数   Passing   Arrays   Function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!