Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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};

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;

   for (i = 0; i < SIZE; ++i)
      printf("%d ", w.a[i]);
Alex Oren
Comment and Contribute






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



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