Would like to know how it works (swap function and sort function in C)
I am new to C and I would like to understand these two functions:
Swap function:
void swap(int a, int b) {
int temp=a;
a=b;
b=temp;
printf("In swap\n");
printf("a: %d\n", a);
printf("b: %d\n", b);
}
Using:
int a=5, b=7;
swap(a, b);
Sort function:
void sort(int values[], int n)
{
for (int i=1; i < n; i++) {
int element=values[i];
int j=i;
while ((j > 0) && (values[j-1] > element)) {
values[j]=values[j - 1];
j--;
values[j]=element;
}
}
return;
}
Using:
int array={9, 1, 8, 5, 3, 2, 5};
int size=7;
sort(array, size);
My question is, why didn't the swap function return with changed values? If the values ββpassed to the swap function take different addresses (I think) so that the values ββoutside the function are not swapped, then why does the sort function return the array sorted? Does this mean that the values ββin the array passed to the sort function have the same addresses?
source to share
As you can imagine, C is called by value, so what is sent to the swap function are copies of the original values, and these are only the copies that have been replaced.
Arrays are a little special in C. Most of the time, when you write the name of an array in a C program, it is converted to a pointer to its first element. So when you try to pass an array to a function, what is actually sent to the function is a pointer to the first element, so any changes to your sort function will be done on the original copy.
source to share
Your swap function won't do anything since you are passing stuff by value and not returning it anywhere.
void swap(int a, int b) {
int temp=a;
a=b; // This is local to the function
b=temp; // Ditto
printf("In swap\n");
printf("a: %d\n", a);
printf("b: %d\n", b);
}
The sort function works due to the decay of the array . When you call your function like
int array[] = { 9, 1, 8, 5, 3, 2, 5 };
int size = 7;
sort(array, size);
the array parameter int values[]
has the equivalent of using it as if it were declared and passed as int* pointer_to_the_first_element_of_the_array
, and thus each use will actually change the original array, not the local copy.
More details on array decaying here .
source to share