Can we use an array as a parameter of the function? If not, how we can change array(global) in function? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Can we use an array as a parameter of the function? If not, how we can change array(global) in function?

19th Sep 2017, 8:28 AM
botenik
3 ответов
+ 9
void func(int arr[]) { //codes } int main() { int arr[5] = {1,2,3,4,5}; func(arr); }
19th Sep 2017, 8:36 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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! :)
20th Sep 2017, 1:23 AM
Zeke Williams
Zeke Williams - avatar
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 }
19th Sep 2017, 8:36 AM
kanishk goel
kanishk goel - avatar