views:

192

answers:

3

I have two string arrays "Array1[size]" and "Array2[size]". They both have the same size. I would like to write a function which contains this two arrays but I am having problems in the way that I am declaring them.

I am declaring it like this: void Thefunction (string& Array1[], string& Array2[], int size);

And when I call it I am calling it like this: Thefunction (Array1, Array2, size);

What I am doing wrong?

Thank you.

+11  A: 

You're declaring a function which takes arrays of string references. You almost certainly want to take arrays of strings.

Like this:

void TheFunction(string Array1[], string Array2[], int size);
Aaron
BTW, arrays of references are prohibited by Standard somewhere in Chapter 8.
Kirill V. Lyadvinsky
Thank you very much!
jualin
If you want to pass the array by value (decayed into a pointer to the first element) this will be one solution, but still, using pointer syntax as in Will's solution will be clearer: http://stackoverflow.com/questions/1683367/how-to-make-two-arrays-into-a-function-in-c/1683381#1683381 . If on the other hand you want to pass the *array by reference* (and there you can omit the size parameter) then follow fnieto's solution: http://stackoverflow.com/questions/1683367/how-to-make-two-arrays-into-a-function-in-c/1684483#1684483
David Rodríguez - dribeas
+4  A: 
void TheFunction(string* Array1,string* Array2,int size) { ... }

Arrays decay into pointers automatically.

Will
In truth, arrays are pointers (and visa versa). The only difference occurrs at declaration, and function parameters aren't declarations.
T.E.D.
@T.E.D: arrays are *not* pointers! When you pass an array, the function receives a pointer. The difference being in the result of the sizeof() operator.
Clifford
@Clifford: Not only the result of the typeof() is different, but the type itself is different. This means that the template type deductions will be different.
David Rodríguez - dribeas
+2  A: 

You can do:

template <std::size_t size>
void TheFunction(string (&Array1)[size], string (&Array2)[size]);
fnieto
+1, this is the only safe solution as the compiler will warrant that the passed in array is of the appropriate size. On the other hand it will not work for dynamically allocated memory.
David Rodríguez - dribeas