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 < SIZE; ++i)      w.a[i] = 0;}void main(){   Wrapper w = { { 1, 2, 3, 4, 5 } };   int i;   f(w);   for (i = 0; i < SIZE; ++i)      printf("%d ", w.a[i]);   puts("");}
See also  11 Effective Keyword Research Tools and Techniques
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist