I'm writing a program in which it would be nice to return an array from a function.
Things are working ok without such a function but for readability and "easy to reuse"
code this would be a nice thing.
Is it possible to do something like that by returning an array? or by reference maybe?
int function(int array)
//read coordinates from a file....
//some stuff here
coord = function(coord);
//more stuff here
Any clues would be greatly appreciated...
Even if you could return an array, you can't assign one array to another. However, there isn't a great need to return arrays either because arrays are passed as pointers when passed as parameters. That means that any changes to the array in the called function will be maintained in the calling function as well. If that isn't the behaviour you want, and you want to keep the array elements unchanged in the functions, then you can use the const keyword to prevent changes from occuring.
To be a little more precise, when you pass an array as in either of the following two situations:
You are doing the exact same thing, passing a pointer to the first element of the array (in this case, arr).
void foo(int* arr);
void foo(int arr);
So, the pointer gets copied (as always with pointer assignment). Any modifications to 'arr' will not affect whatever you passed to it (which is normal for pass-by-value semantics). However, any modifications made to *arr (or arr) persist, as you are actually modifying the value pointed to by the original pointer you passed in as a parameter. So, the same deal for all of the other elements of the array.
You can return an array as well, but only a dynamically allocated one. If you have not yet learned about dynamically allocated memory, I suggest not messing with this.
A good alternative to your problem would be to use std::vectors.
in this case.
I'd still recommend passing that by reference, though, as it is a rather large construct.
ok, thank you both. That is the behavior I was looking for, seems I just didn't understand what
happened when passing arrays as function parameters. But I do now, thanks again!