Consider the following C program:
#include <stdio.h>
void swap(int []);
int main(void) {
int a[3] = {1, 2, 3};
swap(a);
printf("%d %d %d\n", a[0], a[1], a[2]);
swap(&a[1]);
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}
void swap(int x[]) {
int temp = x[0];
x[0] = x[1];
x[1] = temp;
}
Can anyone explain why the following code gives an output
2 1 3
2 3 1
rather than
2 1 3
1 2 3
I understand that swap(a) swaps a[0] and a[1]. But I'm not so sure how swap(&a[1]) works. In both cases we are passing the array a into the function swap, are we not? So my hypothesis was that swap(&a[1]) should again swap a[0] and a[1], giving us back the original order 2 3 1.
EDIT: This code was written as intended. I just wanted to see what happens if we pass an address of an element other than the first element into the function. Apparently if I pass &a[n] into the function, it disregards all elements before a[n] and treats a[n] as the first element?
swap(&a[1])work? In other words, what is going on when we pass into the function an address that is not the first element? Does it then treat&a[1]as the address of the first element?