How can I pass an array as a function parameter?
-
here is what I want to do: I want to swap the some elements of an array so I want to make a function like that: int arr[] // this array is initialized ... swap( int a[]) { //swap parameters } swap(arr); // use the function printarr(arr); // print the resault The question is: how should I pass the array to the function properly, so that it changes the values of arr outside of its body too?
-
here is what I want to do: I want to swap the some elements of an array so I want to make a function like that: int arr[] // this array is initialized ... swap( int a[]) { //swap parameters } swap(arr); // use the function printarr(arr); // print the resault The question is: how should I pass the array to the function properly, so that it changes the values of arr outside of its body too?
-
here is what I want to do: I want to swap the some elements of an array so I want to make a function like that: int arr[] // this array is initialized ... swap( int a[]) { //swap parameters } swap(arr); // use the function printarr(arr); // print the resault The question is: how should I pass the array to the function properly, so that it changes the values of arr outside of its body too?
Pass the array as a pointer.
void SwapArrayVals(int iVals[],int size){
// your code here
}and to call the function
int iData[2] = {11,22};
SwapArrayVals(iData,2);or
int iData[2] = {11,22};
SwapArrayVals(&iData[0],2);Also, it's not always necassary to pass the array size, but it is good practice and avoids writing outside your array.
-
here is what I want to do: I want to swap the some elements of an array so I want to make a function like that: int arr[] // this array is initialized ... swap( int a[]) { //swap parameters } swap(arr); // use the function printarr(arr); // print the resault The question is: how should I pass the array to the function properly, so that it changes the values of arr outside of its body too?
Also, it could be interesting to have a look at the containers (particularly the vector) of the standard template library (STL). Basically, it will help you to maintain arrays that can be resized easily, ...
-
here is what I want to do: I want to swap the some elements of an array so I want to make a function like that: int arr[] // this array is initialized ... swap( int a[]) { //swap parameters } swap(arr); // use the function printarr(arr); // print the resault The question is: how should I pass the array to the function properly, so that it changes the values of arr outside of its body too?