0

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.

Toby
  • 9,696
  • 16
  • 68
  • 132
David
  • 312
  • 3
  • 10
  • Why do you have a c++ tag? Did you notice it? Did you know that c++ is not c with classes? – Iharob Al Asimi Nov 25 '16 at 10:27
  • Also, how does the book define *information hiding*? What is it? – Iharob Al Asimi Nov 25 '16 at 10:28
  • The first version of *swap* is preferred because it does not assume that the parameters come from an array. This makes it more generally applicable. – August Karlstrom Nov 25 '16 at 11:13
  • @iharob I guess I included it becase SO suggested so. Yes I know they are different. Here is how the book define it: **Labels are implementation details that functions hide from one another. This hiding—more formally called information hiding—is a means of implementing the principle of least privilege.....** – David Nov 26 '16 at 00:18

1 Answers1

0

In C, pointers and arrays are interchangeable. When you access array elements by index, as in myArray[x], it means "the location of myArray + (x * the size of the elements in the array)". So you can get the same result by doing myArray + (x * sizeof(<type of myArray>));.

You may also want to check out this answer which goes into more depth on the differences between arrays and pointers.

Community
  • 1
  • 1
Nico
  • 2,645
  • 19
  • 25