Welcome to MSDN Blogs Sign in | Join | Help

Passing C++ Arrays by Value

Just in case you needed to, you can wrap an array into a struct/class and pass it by value to a function:

template<typename T, int N>
struct array {
    T value[N];
    T & operator[](int i) { return value[i]; }
};

template<typename T, int N>
void passByValue(array<T, N> a) {
    cout << "Value in function:" << endl;
    for (int i = 0; i < N; i++) a[i] = 1, cout << a[i] << endl; // prints 1's
}

int main() {
    const int N = 5;
    array<int, N > a;

    for (int i = 0; i < N; i++) a[i] = 0;

    passByValue(a);

    cout << "Value after function call:" << endl;
    for (int i = 0; i < N; i++) cout << a[i] << endl; // prints 0's

    return 0;
}

Published Saturday, August 08, 2009 3:01 AM by mohamedg
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Passing C++ Arrays by Value

An good example about template :)

Saturday, August 08, 2009 5:36 AM by jack17

# re: Passing C++ Arrays by Value

That's a real cool stuff.

:-)

Thanks for this post.

Saturday, August 08, 2009 7:09 AM by seo2

# re: Passing C++ Arrays by Value

I have often used such a struct. With more extended use, I had to add a const version of operator[], to maintain array semantics. When I'm not passing the array by value, I would need a const version (constant reference) -- I shouldn't have to unbox the array:

 const T& operator[](int i) const { return value[i]; }

To use your output example:

 template<typename T, int N>

 void print(const array<T, N>& a) {

   for (int i = 0; i < N; i++) cout << a[i] << endl;

 }

While we're at it, what if I want to pass the array to an STL algorithm (or another that uses iterators), or need to grab hold of the array itself?

 T* operator&() { return value; }

 T* const operator&() const { return value; }

So you can do, say:

 sort(&a, &a+N);

It does look a bit ugly when you actually use it, but hey, this is C++. :-)

Saturday, August 08, 2009 7:20 AM by Remoun Metyas

# re: Passing C++ Arrays by Value

Take a look at boost:array.

Dejan

Saturday, August 08, 2009 1:54 PM by djelovic

# re: Passing C++ Arrays by Value

@Remoun Great addition indeed.

@djelovic I hope boost makes it to the standards in 2010

Saturday, August 08, 2009 9:29 PM by mohamedg

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker