puzzlecracker said:
The only way to pass an array by value is to encapsulate it in a struct:
#include <iostream>
struct Array {
int A[10];
};
void f(Array a) {
int* A = a.A;
for (size_t j = 0; j < 10; ++j)
std::cout << ' ' << A[j];
std::cout << std::endl;
}
this is not going to work - you need to define a copy constructor,
otherwise you still passing an address fo the first element i.e. not
copied first element. please correct me if I am wrong!
You are wrong in this case, because the array is statically initialized.
You would be correct if it were dynamically initialized, as in the following
example:
#include <iostream>
#include <iterator>
#include <algorithm>
class Array {
int* p_;
size_t sz_;
public:
typedef int* iterator;
typedef const int* const_iterator;
iterator begin() {return p_;}
iterator end() {return p_ + sz_;}
const_iterator begin() const {return p_;}
const_iterator end() const {return p_ + sz_;}
Array(size_t sz) : p_(new int[sz]), sz_(sz) {}
Array(Array const& a) : p_(new int[a.sz_]), sz_(a.sz_) {
std::copy(a.begin(), a.end(), begin());
}
~Array() {
if (p_) {
delete [] p_;
p_=0; sz_=0;
}
}
};
void print(Array a) { // pass by value
using std::copy;
using std::cout;
copy(a.begin(), a.end(), std:
stream_iterator<int>(cout," "));
cout << std::endl;
}
int main() {
Array a(10);
Array::iterator in=a.begin();
for (int i=0; in!=a.end(); ++in,++i)
*in=i;
print(a);
}