I am trying to write an exchange sort in c using pointers, NOT indices;
I do not understand why this code does not work:
void sort(int a[], int n) {
int *i, *j, *temp;
int * const end = a + n;
for(i = a; i < end - 1; i++)
for(j = i + 1; j < end; j++)
if(*i > *j) {
temp = i;
i = j;
j = temp;
}
}
If I write this code in main, a swap works fine:
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int *i = a;
int *j;
int *temp;
i = a;
j = a + 1;
printf("pre-swap - i: %i | j: %i\n", *i, *j);
temp = i;
i = j;
j = temp;
printf("post-swap: i: %i | j: %i\n", *i, *j);
It successfully swaps the two values.
But it does nothing to the array when I use this code:
sort(a, 10);
Why isn't my sort algorithm working?
temp = i; i = j; j = temp;->temp = *i; *i= *j; *j=temp;andint temp;a[]remain where they were. The only way to change something pointed to by a pointer is via dereference, which you should be familiar with, as you're using it to both compare and print values. Remember: pointers hold addresses. You need to dereference pointers to get to what that point to.