[英]Using an Array being passed by a function.
// This program demonstrates an array being passed to a function
#include <iostream>
using namespace std;
void showValues(int [], int) ; //Function prototype.
int main()
{
const int ARRAY_SIZE = 8;
int number [ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40};
showValues (number, ARRAY_SIZE);
return 0;
}
//Definition of function showValue.
//This function accpets an array to integers and
//the array's size as its arguments. The contents.
//of the array are displayed.
void showValues (int nums[], int size)
{
for (int index = 0; index < size; index++)
cout << nums [index] << " ";
cout << endl;
}
Using C++, Studying arrays, the program works fine, however; 使用C ++,研究数组,该程序可以正常工作。 I am not understanding the for loop on the bottom where it says "index < size" Where is "size" getting its value from that the for loop knows when to stop looping? 我不了解底部显示“索引<size”的for循环,for循环知道何时停止循环,“ size”从何处获取其值?
size
is passed as a parameter to the function showValues
. size
作为参数传递给函数showValues
。
That function is called from main()
, passing ARRAY_SIZE
as that parameter. 该函数从main()
调用,并传递ARRAY_SIZE
作为该参数。
ARRAY_SIZE
is defined as the size of the array. ARRAY_SIZE
定义为数组的大小。
Actually, you could write 其实你可以写
int number [] = {5, 10, 15, 20, 25, 30, 35, 40};
since the compiler can figure out the array size from the initialisation array. 因为编译器可以从初始化数组中找出数组的大小。 The function call can be refactored to 函数调用可以重构为
showValues(number, sizeof(number) / sizeof(int));
sizeof(number) / sizeof(int)
is an idiomatic way of evaluating the number of elements in an array. sizeof(number) / sizeof(int)
是一种惯用的评估数组中元素数量的方法。 Some folk prefer sizeof(number) / sizeof(number[0])
since then the code is not sensitive to the type of the array. 一些人更喜欢sizeof(number) / sizeof(number[0])
因为这样代码对数组的类型不敏感。 You can then remove ARRAY_SIZE
entirely. 然后,您可以完全删除ARRAY_SIZE
。
The showValues (number, ARRAY_SIZE);
showValues (number, ARRAY_SIZE);
call 呼叫
passes the array as well as its size to void showValues (int nums[], int size)
将数组及其大小传递给void showValues (int nums[], int size)
Therefore size in the for loop gets the value 8 因此,for循环中的大小为8
void showValues (int nums[], int size)
The second parameter to the function showValues becomes the size in your for loop. 函数showValues的第二个参数成为for循环中的大小。
const int ARRAY_SIZE = 8;
showValues (number, ARRAY_SIZE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.