(This looks like a homework question.)
void square(int array[])
{
int size = sizeof(array)/sizeof(array[0]);
Here you have a major bug, which you would have noticed if you had compiled and run your code before posting it. Because array
is a function parameter of type int*
, sizeof(array)
is the same as sizeof(int*)
. Therefore you square only the first 1 or 2 elements of your input array.
The most common idioms for passing around arrays in C++ are
void square(int *array, size_t length); // a.k.a. "the C way"
void square(std::vector<int>& array); // a.k.a. "dodging the question"
void square(int *begin, int *end); // the STL does this, but template-ized
void square(int (&array)[5]); // Pass an array by reference (not very useful as you need to specify the size)
template<int N>
void square(int (&array)[N]); // Use a template to make passing an
// array by reference useful.
// Note: You now no longer need to calculate the size (its N)
I guess my favorite "too advanced" answer for this one would be
#include <iostream>
template<class Array>
void square(Array& array) {
for (auto& elt : array) {
elt *= elt;
}
}
int main() {
int array[] = {2,4,6,8,10};
square(array);
for (auto i : array) {
std::cout << i << " ";
}
std::cout << std::endl;
}
square
the number of elements inarray
are not known.sizeof(array)
will be equivalent tosizeof(int*)
. This make the function producing wrong values. \$\endgroup\$int size = sizeof(array)/sizeof(array[0]);
If you looked at your compiler warnings it will tell you this. When an array is passed as a parameter it decays into a pointer. So at the other endsizeof(array)
will return you the size of a pointer. \$\endgroup\$