In the Chapter 7 of Deitel's C how to program the author used bubble sort example to show that information hiding does not allow individual array elements to be known to the function, pointers can be used to pass the address around and used the same way.
Here is the swap function using pointer:
void swap( int *element1Ptr, int *element2Ptr ) {
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}
Here is what I did:
void swap(int array[],int j) {
int hold = array[j];
array[j] = array[j + 1];
array[j + 1] = hold;
}
The main():
int main(void) {
int b[] = {2,6,4,8,10,12,89,68,45,37};
for (int i = 0; i < 9; i++) {
for (int n = 0; n < 9; n++) {
if (b[n] > b[n + 1]) {
swap(&b[n], &b[n+1]); // or swap(b,n);
}
}
}
for (int i = 0; i < 9; i++) {
printf("%d ", b[i]);
}
puts("");
return 0;
}
I ran the code and both sort the array correctly. So I thought my function actually gained the access to individual element. Which part am I understanding wrong? I need to make sure I understand every point before moving on as skipping one really makes the coming content difficult to grasp.