devxlogo

Passing Arrays by Value

Passing Arrays by Value

It has already been said many times that (a) std::vector is preferred to c-style arrays, and (b) Arrays, vectors, and other data structures should preferably be passed by reference.
While this is sound advice in the general case, there may come a time when you want to pass a c-style array by value.
This is not simple since arrays decay to pointers on function calls. So, if you have:

    int a[] = { 1, 2, 3, 4, 5};   f(a);

The actual argument to f() is a pointer to the first element of the array. In order to overcome it, wrap the array in a structure. This technique works both in C and C++, so I’ll demonstrate it without using C++ specific features:

 #include &;t;stdio.h>#define SIZE 5typedef struct{   int a[SIZE];} Wrapper;void f(Wrapper w){   int i;   for (i = 0; i 

devx-admin

Share the Post: