c++ - Passing values of array to a function that modifies the value then returns it into a new array -


i'm having trouble getting code return correct arrays. void map takes in function such tiple , modifies value passed array src , returns new value dst printed out. can code compile doesn't return correct array. example, when takes in [1,2,3,4] returns [0,3,6,9] instead of [3,6,9,12]

typedef int (*intmodifier)(int);  int triple(int x){     return 3*x; }  void map(intmodifier func, int src[], int dst[], int length){     for(int *i = src; < src + length; ++i){     dst[*i] = func(*i);     } return;  }  void printintarray(int arr[], int length){ cout << "{";     if (length > 0){     cout << arr[0];     }     for(int = 1; < length; ++i){     cout << ", " << arr[i];     }     cout << "}";     }  int main(){  int arr1[4] = {1, 2, 3, 4}; int arr2[4] = {0, 0, 0, 0}; int arr3[4] = {0, 0, 0, 0}; int arr4[4] = {0, 0, 0, 0};  cout << "testing map." << endl; cout << "  setting arr1 = {1,2,3,4}" << endl << endl;  cout << "  mapping arr1 arr2 using triple" << endl; map(triple, arr1, arr2, 4); cout << "  arr2 = "; printintarray(arr2, 4);  cout << endl << endl; return 0; } 

any appreciated. thanks.

i not sure why second element being modified. fact 1 this:

void map(intmodifier func, int src[], int dst[], int length){     for(int *i = src; < src + length; i++){         dst[*i] = func(src[*i]);         return; // return here!!!     } } 

you return map during first iteration of for loop. see how beneficial indent code!


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -