Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void swap(int *a, int *b) not working with array

New to C programming and in the attempts to make a void function that swaps the values of two variables. When I wish to swap the values of two integer variables the following functions works just fine for lets say a = 11, b = 33 with function call swap(&a, &b):

void swap(int *a, int *b) {
  *a += *b;
  *b = *a - *b;
  *a -= *b; 
}

But when I try to do this with two elements of an array it does not work correctly for swap(&a[0], &a[2]) for example. It does however work with the following function:

void swap(int i, int j, int a[]) {
  int h = a[i];
  a[i] = a[j];
  a[j] = h;
}

Does anyone know why the first works of single variables but not with array elements? Sure there is a very good explanation that I am missing here. All help is welcome, thanks in advance!!

Here is the complete program:

#include <stdio.h>
#include <stdlib.h>


void swap(int *a, int *b) {
  *a += *b;
  *b = *a - *b;
  *a -= *b; 
}

void selectionSort(int a[], int len) {
  int i, j, min;
  for (i = 0; i < len; i++) {
    min = i;
    for (j = i+1; j < len; j++) {
      if (a[j] < a[min]) {
        min = j;
      }
    }
    swap(&a[i], &a[min]);
  }  
}

int main(int argc, char * argv[]) {
  int a[5] = {5, 4, 3, 2, 1};
  int len = 5, i;

  selectionSort(a, len);


  for (i = 0; i < len; i++) {
    printf("%d ", a[i]);
  }
  printf("\n");

    return 0;
}

Output for the array values is 1 2 0 0.

like image 641
jake1992 Avatar asked Feb 01 '26 22:02

jake1992


1 Answers

Let me guess -- all the values turn to zeroes?

Your swap function is broken if a == b. Try:

void swap(int *a, int *b) {
  if (a != b)
  {
      *a += *b;
      *b = *a - *b;
      *a -= *b; 
  }
}
like image 159
David Schwartz Avatar answered Feb 04 '26 15:02

David Schwartz



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!