table passed to function "by value"

Is it possible in C++ to pass a table of integers to some function "by value"? so that even when I change the table in that specific function it will remain unchanged in the "main" program?
wrewersAsked:
Who is Participating?
 
curriConnect With a Mentor Commented:
Yo can NOT pass an array by value; however you can put the array inside a structure and pass that structure by value.

like
struct cheat {
      int t[4];
};

cheat t={{1,2,3,4}}
etcetera

0
 
wrewersAuthor Commented:
Edited text of question.
0
 
wrewersAuthor Commented:
I meant something like this:

int suma(int tab[4])
{
  int i,outcome=0;
  for(i=0;i<3;++i) outcome+=tab[i];
  tab[3]=outcome;
  return outcome;
};

int main(void)
{
  int t[4]={1,2,3};
  suma(t);
  return 0;
};
0
 
KangaRooCommented:
This will work properly if you use std::vector
0
 
jasonclarkeCommented:
You can't do it with simple arrays in the way you want (remember as far as the compiler is concerned there is no difference between an array and a pointer:

  array[i] is equivalant to *(array+i)

if you want to pass C arrays by value you would have to make a copy in the function that wants it.  (This can be fairly efficient, because at least with simple C arrays you can use memcpy or something like it).

The best thing is to do as KangaRoo suggests, use a better container than a simple array, and the STL vector is probably the container of choice for this sort of thing.
0
All Courses

From novice to tech pro — start learning today.