+ 2

How to pass an array using call by value ? { I have declared an array locally in main and don't want its value to be modified by some other function}

13th Sep 2016, 6:31 PM
Simant |Kingpin|
Simant |Kingpin| - avatar
4 odpowiedzi
+ 2
Passing an array by value is not recommended. Instead, use const to prevent the function from modifying it. int myfunc(const int* arr) { ... }
13th Sep 2016, 6:51 PM
Zen
Zen - avatar
+ 1
u can call a fn by value using recursion... i mean u can call that fn using loop and send the value stored in array one by one...
14th Sep 2016, 4:46 AM
subodh Kumar
subodh Kumar - avatar
+ 1
My bad, I could have guessed you wanted to be able to change the array. I checked, and C++ doesn't even allow you to pass an array by value. So you should make a copy of it at the beginning of your function. #include <iostream> #include <iterator> using namespace std; void myfunc(const int arr[5]) { int i; int arr_copy[5]; copy(arr, arr+5, arr_copy); for (i = 0; i < 5; i++) { arr_copy[i]--; cout << arr_copy[i] << " "; } } int main() { int arr[5] = {11, 22, 33, 44, 55}; myfunc(arr); return 0; } (If your array doesn't have a fixed size, use void myfunc(const int *arr, int len) instead for example.)
14th Sep 2016, 9:26 AM
Zen
Zen - avatar
0
But now the called function won't be able to modify it ?
13th Sep 2016, 7:14 PM
Simant |Kingpin|
Simant |Kingpin| - avatar