+ 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}
4 Respuestas
+ 2
Passing an array by value is not recommended. Instead, use const to prevent the function from modifying it.
int myfunc(const int* arr) {
...
}
+ 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...
+ 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.)
0
But now the called function won't be able to modify it ?