i dont understand why this doens't work, i want to get an arraym(in my main app 2) and do some stuff with it and then return the array of result ( all of arrays have 2 slots!
Remember that the function is returning a pointer, not an array. You can't use the assignment operator to assign variables of different types, a pointer is not an array. You could try something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int * tellarr(int array[])
{
for(int i=0;i<2;i++)
array[i]++;
return array;
}
int main(){
int arr[2] = {20,45};
int *retArray = tellarr(arr);
cout << retArray[0] << endl;
cout << retArray[1] << endl;
return 0;
}
Array parameters are by reference. Calling tellarr does not copy values from arr into array. When you modify array[1] in tellarr, you actually modify the memory location of arr[1] in main(). Thus, returning void is just as good.
Your thread title; "get 2, give 1" ... does not seem to relate to your question.
As jlb said you are trying to assign a pointer ( int * ) to an ineteger array, "arr" must be a pointer to an integer too or simply "int *" this should do the trick:
@fevzi
That is scary. First, you give a pointer to function that expects an array. At first glance that would be same as storing the returned pointer as array, like in OP's post.
Much worse is that you allocate space dynamically and then overwrite the pointer that had the address of that space. How were you planning to deallocate the memory block? (Granted, in this case the function supposedly returns the same address that you give as parameter, but one should not trust somebody else's code unnecessarily.)
Keep it simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
using std::cout;
void tellarr( int array[], int n )
{
for ( int i=0; i < n; ++i ) ++array[i];
return array;
}
int main()
{
constint size = 2;
int arr[size] = {20,45};
tellarr( arr, size );
for ( int i=0; i < size; ++i ) cout << arr[i] << '\n';
return 0;
}