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?
CodePudding user response:
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.
CodePudding user response:
Your formal argument must have the same type as your factual.
If you try to call with std::array<int, 5>
then declare your function like void myFunction(std::array<int, 5> arr)
.
Need to know that such declaration means copy your array. It may have no need. Then you may use a reference.
If need just to read without change and move then const lvalue
reference is enough. Ready prototype:
void myFunction (std::array<int,5> const &arr);
CodePudding user response:
If you can compile with C 20, I would strongly suggest you change your function to:
void myFunction(std::span<const int> arr) {
for (const int elm : arr) {
std::cout << elm << std::endl;
}
}
By using span as the parameter, your function can be called with any type of continous int of any size, eg.
std::vector<int> vec{1,2,3};
std::array arr{1,2,3,4,5};
int oldArray[4] = {1,2,3,4};
myFunc(vec);
myFunc(arr);
myFunc(oldArray);