将数组传递给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<< \\\
;
}
}
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 []
?
int []
b $ b
和
int [X] //其中X是编译时正整数
与
完全相同 int *
当在函数参数列表中时
此外,数组名称传递给函数时不会衰减到指向第一个元素的指针(而不是通过引用传递),因此 int firstarray [3]
和 int secondarray [5]
衰减到 int *
p>
也会发生数组解引用和指针解引用下标语法(下标语法 x [y]
)
这三个规则组合起来使得代码合法,并按照你的期望工作;它只是传递指向函数的指针,以及在数组衰减到指针后你不能知道的数组长度。
#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[]
?
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.
这篇关于将数组传递给C ++中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!