Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping two pointers to pointers

Tags:

arrays

c

pointers

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;
}
like image 609
user3270760 Avatar asked May 15 '26 01:05

user3270760


1 Answers

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]);
}
like image 88
David Heffernan Avatar answered May 17 '26 13:05

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!