So, I have declared an array using the <array> header in C++, and now I want to pass this array to a function that doesn't return any value but displays each element in a new line on the terminal. Following is the code for that.
// to pass an array to a function
#include <iostream>
#include <array>
using namespace std;
void myFunction(int arr[5]); // function prototype
int main () {
array <int, 5> arr{1, 2, 3, 4, 5};
myFunction(arr);
}
// function definition
void myFunction(int arr[5]) {
for (size_t counter{0}; counter < 5; ++counter) {
cout << arr[counter] << endl;
}
}
The above code isn't working.
arr no suitable conversion function from "std::array<int, 5ULL>" to "int *" existsC/C++(413)
...
demo.cpp: In function 'int main()':
demo.cpp:11:16: error: cannot convert 'std::array<int, 5>' to 'int*'
11 | myFunction(arr);
| ^~~
| |
| std::array<int, 5>
demo.cpp:6:21: note: initializing argument 1 of 'void myFunction(int*)'
6 | void myFunction(int arr[5]); // function prototype
|
These two are the error messages getting shown to me. Now on the other hand, if I declare the array differently, without using the standard library header, it works fine.
arr[5] {1, 2, 3, 4, 5}; // instead of
// array <int, 5> arr{1, 2, 3, 4, 5};
It produces the following result
1
2
3
4
5
I just want to know what the array declarations have to do with any of this? If there is a way of doing this using the declaration with <array> header, what is it?
The problem is that your function expects an int*
but you're passing a array <int, 5>
but since there is no implicit conversion from array <int, 5>
to int*
, we get the mentioned error.
You can also use std::array::data
as myFunction(arr.data());
to make this work.
The reason your second case works when you create array like int arr[5] {1, 2, 3, 4, 5};
and then pass it like myFunction(arr)
is because a built in array decays to a pointer to its first element(int*
in your example) due to type decay. So in this modified case, the type of the argument and the parameter matches and this works.