First note that std::array
has no operator+
. So when you wrote the expression:
*arr+2 // INCORRECT
In the above expression, you are dereferencing the pointer to std::array
and then adding 2
to the result. But as i said at the beginning, that there is no operator+
for std::array
, this expression is incorrect.
Limitation
Second you program has a limitation which is that the function print
can accept a pointer to an std::array
with only 6
elements. So if you try to pass a pointer to an std::array
of some different size then your program won't work.
Solution
You can fix these by:
- Passing the
std::array
by reference.
- Using templates. In particular, using template nontype parameter.
The advantage of using template nontype parameter is that now you can call the function print
with an std::array
of different size as shown below.
#include <iostream>
#include <array>
template<std::size_t N>
void print(std::array<int, N> &arr){ //by reference
for(const int &i : arr){
std::cout<<i<<" ";
}
arr.at(2) = 2; //use at() member function so that you don't get undefined behavior
std::cout<<std::endl;
}
int main(){
std::array<int, 6> arr2={1, 2, 3, 4, 5, 6};
print(arr2);
std::array<int, 10> arr3 = {1,2,4,3,5,6,7,8,9,10};
print(arr3);
}
Some of the modifications that i made include:
- Removed
#include <bits/stdc++.h>
and only included headers that are needed.
- Used templates. In particular, removed the limitation by using template nontype parameter.
- Passed the
std::array
by reference. That is, there is no need to pass a pointer to an std::array
. We can just pass the std::array
by reference.
- Used
at()
member function so that we don't go out of bounds and so that we don't get undefined behavior.