I usually use vectors in C++, but in a particular case I have to use arrays which I'm not used to. If I do this:
// GetArraySize.cpp
#include <iostream>
#include <conio.h> // remove this line if not using Windows
int main(void)
{
int myArray[] = { 53, 87, 34, 83, 95, 28, 46 };
auto arraySize = std::end(myArray) - std::begin(myArray);
std::cout << "arraySize = " << arraySize << "\n\n";
_getch(); // remove this line if not using Windows
return(0);
}
This works as expected (arraySize prints out as 7). But if I do this:
// GetArraySizeWithFunc.cpp
#include <iostream>
#include <conio.h> // remove this line if not using Windows
// function prototypes
int getArraySize(int intArray[]);
int main(void)
{
int myArray[] = { 53, 87, 34, 83, 95, 28, 46 };
int arraySize = getArraySize(myArray);
std::cout << "arraySize = " << arraySize << "\n\n";
_getch(); // remove this line if not using Windows
return(0);
}
int getArraySize(int intArray[])
{
auto arraySize = std::end(intArray) - std::begin(intArray);
return((int)arraySize);
}
On the line auto arraySize = std::end(intArray) - std::begin(intArray);
I get the error:
no instance of overloaded function "std::end" matches the argument list, argument types are: (int *)
What am I doing wrong?
I should mention a few things:
-I'm aware that with C++ 17 I could use std::size(myArray), but in the context I'm working in I can't use C++ 17
-There may be other / better ways to write a getArraySize() function, but moreover I'm trying to better understand how old-style arrays are passed into / out of functions
int main(void)should beint main(). Andreturn(0);should bereturn 0;. Andreturn((int)arraySize);should bereturn (int)arraySize;. Instead of a C array, you should usestd::array. If you insist on passing in a C array, you should also pass in its length (if its length is something you care about). Soint getArraySize(int arraySize) { return arraySize; }, which is a bit redundant.main(void)should be replaced withmain(). Also the return type should beint.static_cast.std::size(x)will only works whenstd::end(x) - std::begin(x)works so using C++ 17 would not help. C style arrays do not carry their size across function as the decay to pointers.