Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
May 13, 2002

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 5

typedef 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("");
}
Alex Oren
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date