Consider the following questions:
# Include <iostream>
Using namespace std;
Int Sum (int I [])
{
Int sumofi = 0;
For (int j = 0; j <sizeof (I)/sizeof (int); j ++) // actually, sizeof (I) = 4
{
Sumofi + = I [j];
}
Return sumofi;
}
Int main ()
{
Int allAges [6] = {21, 22, 22, 19, 34, 12 };
Cout <Sum (allAges) <endl;
System ("pause ");
Return 0;
}
Sum is used to get the size of the array with sizeof, and then Sum. But in fact, the Input Self-function Sum is only a pointer of the int type, so sizeof (I) = 4, not 24, so it will produce an error. To solve this problem, use a pointer or reference.
Pointer usage:
Int sum (INT (* I) [6])
{
Int sumofi = 0;
For (Int J = 0; j <sizeof (* I)/sizeof (INT); j ++) // sizeof (* I) = 24
{
Sumofi + = (* I) [J];
}
Return sumofi;
}
Int main ()
{
Int allages [] = {21, 22, 22, 19, 34, 12 };
Cout <sum (& allages) <Endl;
System ("pause ");
Return 0;
}
In this sum, I is a pointer to the I [6] type. Note that int sum (INT (* I) []) cannot be used to declare a function, instead, you must specify the size of the array to be passed in. Otherwise, sizeof (* I) cannot be calculated. However, in this case, it is meaningless to use sizeof to calculate the array size, because the size is set to 6.
The reference is similar to the pointer:
Int sum (INT (& I) [6])
{
Int sumofi = 0;
For (Int J = 0; j <sizeof (I)/sizeof (INT); j ++)
{
Sumofi + = I [J];
}
Return sumofi;
}
Int main ()
{
Int allages [] = {21, 22, 22, 19, 34, 12 };
Cout <sum (allages) <Endl;
System ("pause ");
Return 0;
}
In this case, sizeof calculation is meaningless. Therefore, an array is used as a parameter. When traversal is required, the function should have a parameter to describe the size of the array, the size of the array is evaluated by sizeof within the scope defined by the array. Therefore, the correct form of the above function should be:
# Include <iostream>
Using namespace STD;
Int sum (int * I, unsigned int N)
{
Int sumofi = 0;
For (Int J = 0; j <n; j ++)
{
Sumofi + = I [J];
}
Return sumofi;
}
Int main ()
{
Int allages [] = {21, 22, 22, 19, 34, 12 };
Cout <sum (I, sizeof (allages)/sizeof (INT) <Endl;
System ("pause ");
Return 0;
}