I am trying to create a function that returns the length of an array. I am running into endless problems, I believe because it will only point at the array, not actually refer to the entire array. Here is my code, which consistently returns "1". Does anybody know how I can do this? Thanks!
When you pass an array to a function, it decays into a pointer to the first element. So sizeof(input_array) returns the size of a pointer on your system, not the size of the entire array.
Addition:
I believe this code can do what you want.
You should be able to just use it like a normal function; the compiler should be able to figure out the template parameters on it's own. Just make sure you pass it an actual array, not a pointer.
I think I am almost there, but I am getting an error:
g++ test.c++ functions.h; ./a.out
test.c++: In function ‘int main()’:
test.c++:13: error: no matching function for call to ‘array_length(std::string*&)’
Would that mean that I am not sending it an actual array?
Okay, thank you. If I want to define the array in a separate function (say in a header file) and be able to get the length in the main program, is there a way to do that, or would I be better to append a special character in the last element or something along those lines?
You'll probably need to. Anytime you pass an array, it will decay to a pointer and the compiler will no longer know how long it is. Depending on what you are doing, however, it could be much easier to simply use a vector instead.
#include <iostream>
#include <vector>
usingnamespace std;
int main (void)
{
constdouble numbers[] = {0, 1, 2, 3, 4};
vector<double> theArray (numbers, numbers + 5);
/**
Now you can pass theArray to anywhere.
Its size information will go with it.
You can do many more with it.
Refer to vector section in STL documentation.
**/
cout << "The length of the array is " << theArray.size () << endl;
return 0;
}
Change 'vector<double>' to 'vector<char>' if you want to create an array of character. However you will not certainly do this. Because C++ STL provides std::string as a pre-fabricated class which inherently contains an array of character. Thus the following code will print the length of a string.
1 2 3 4 5 6 7 8 9
#include <string>
#include <iostream>
usingnamespace std;
int main (void)
{
string str = "What is the length of this string?";
cout << "Length = " << str.size () << endl;
}
If you want to pass the string to a function as an argument, pass its reference.
1 2 3 4
int findStringLength (const std::string &str)
{
return str.size ();
}
or
1 2 3 4
int findStringLength (const std::string *str)
{
return str->size ();
}
Note that, the reference is sent as 'const std::string &' or 'const std::string *'. The object is not copied. The 'const' is recommended because the value of the string is not intended to be changed inside the function.