I have a function which takes a pointer to an array (so an int**). In this function, I'd like to call swap(int*, int*) to swap the location of two of the elements in the array. What is the syntax in C for swapping these two elements?
Here's an example of what I'm looking for:
int* do_something(int** arr) {
// assume i and j are valid locations in the array
swap(&arr[i], &arr[j]); // what should this line be?
}
// this function works fine, no changes needed
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
It's not clear to me what arr is. Is it an array of int*, or is it a pointer to an array of int?
Option 1: arr is an array of int*:
Your swap function swaps int variables, but you need to swap int* variables. You therefore need an extra level of indirection in the swap function.
void swap(int** a, int** b)
{
int* temp = *a;
*a = *b;
*b = temp;
}
Option 2: arr is a pointer to an array of int:
In this case, you wish to swap two int values, and the variant of swap that appears in the question does just that. The problem is that you have defined do_something incorrectly. It should receive an int* and be implemented like this:
void do_something(int* arr, int i, int j)
{
swap(&arr[i], &arr[j]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With