Reputation: 1644
I am trying out a c++11 array by following along with this YouTube video tutorial series. Though I am not very skilled in using my IDE's, I have both of my IDE's, Eclipse and Codeblocks, set to have the compiler follow the C++0x ISO language standard [-std=c++0x] which at least allows them to understand the syntax of a c++11 array, such as array <double, 5> rainfall;
Both are responding in the same way. The following code I have written passes this array to a function which prints it out.
#include <iostream>
#include <array>
using namespace std;
void printArray(double[], int);
int main()
{
array <double, 5> rainfall;
rainfall[0] = 2.3;
rainfall[1] = 0.3;
rainfall[2] = 0.0;
rainfall[3] = 4.1;
rainfall[4] = 0.5;
printArray(rainfall, 5);
return 0;
}
void printArray(double array[], int size)
{
for(int i = 0; i < size; i++)
{
cout << array[i] << " | ";
}
}
With a non-c++11 array, such as double rainfall[5]
this works fine, but with array <double, 5> rainfall
there is an error which reads cannot convert 'std::array<double, 5u>' to 'double*' for argument '1' to 'void printArray(double*, int)
The video I am following uses the same code, yet does not receive this error.
Upvotes: 3
Views: 3113
Reputation: 132994
You could pass rainfall.data()
to the function. An std::array<T, N>
is not implicitly convertible to T[N]
.
Upvotes: 4
Reputation: 183
As you can see, in the video you use, the guy uses a static, c-style array which can be implicitly converted to T* BUT you are using an c++11 array, which doesn't have implicit conversion to static array. Though, C++11's array class has method data which gives you direct access to the underlying data, which will do in your case.
But in this case, if you want to use the function with c++11 arrays, you can make an overload like this:
template <typename T, size_t Size>
void printArray(const std::array<T, Size>& arr);
This would work with any size and you don't need to pass another (unneeded) parameter for size ;)
Upvotes: 9
Reputation: 2885
Or you can define the function as
void printArray (const array <double, 5>& myarray, int size)
Upvotes: 2