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.
*a ^= *b; *b ^= *a; *a ^= *b;Still doesn't work whena == b.