+ 1
Can we use an array as a parameter of the function? If not, how we can change array(global) in function?
3 Answers
+ 9
void func(int arr[])
{
//codes
}
int main()
{
int arr[5] = {1,2,3,4,5};
func(arr);
}
+ 2
If you are looking to "change" the array when you pass it into a function, you will need to use an array reference, or pointer. Because of this, you lose the size of the array, so you will need to pass that into the function as well:
void func(int* arr, int size) {
for (int i = 0; i < size; ++i) {
arr[i] += 1;
}//this will increment every element by one
}
int main() {
int arr[] = {4, 6, 9, 0};
void func(arr, sizeof(arr));
//arr is now changed in the scope of main()
cout << arr[0] << endl; // this outputs 5
}
NOTE** try not to use global variables...ever. Happy Coding! :)
0
yes you can use array as a parameter of the function.
a[3] =[1,2,3]
multiply(a) \\ pass array as parameter
public int multiply(int a[])
{
\\ rest code here
}