tags:

views:

60

answers:

2

I am implementing the standard bubble sort algorithm, and I had a question on pointers.

float *SortValues(float *p, size_t n)
{
    float temp;
    float didSwap;
    float *current;
    float *last = &p[n - 1];
    float *start = p;

    do 
    {
        for (didSwap = 0, current = p; current < last; current++) {
            if (current[0] > current[1]) {
                temp = current[0];
                            current[0] = current[1];
                current[1] = temp;
                didSwap = 1;
            }
        }
        --last;
    }

    while (didSwap);
    return start;
}

I get confused a lot of times using other pointers to point to the start and/or end of the pointer passed in. In something like the code above, I set current to point to p, and start to point to p. The current changes throughout the loop. Since current and p point to the same thing, how does p, and therefore start end up changing to pointing to the same thing as current?

+1  A: 

Where start is pointing doesn't change. What start is pointing at does.

Imagine you have five cups and you put a ball in the green one. Then you tell me to replace the ball in the green cup with a dollar bill. Next time you look in the green cup, it will contain a dollar, not the ball you put there.

The last time through the while loop, when last == start, only the initialization of the for loop is executed so that current == p when the while loop exits.

David Kanarek
+1 for good analogy. :-)
Tim
A: 

Subscripts vs. Pointers


Right now the code is written with a hybrid approach that uses some subscripting and some pointer addressing.

It's possible that if you rewrote this loop to work entirely with subscripts instead of the current hybrid addressing, then it would be easier to understand.

For that matter, it could be written to use entirely pointers with no subscripts.

I'm not complaining about the current organization which looks just fine, I'm just saying that it might shed some light on the implementation to see it done both ways in pure form.

But to answer your question, keep in mind that the list is always in the same location, it's just that elements have their values swapped. So the beginning of the list is always in the same place, but it doesn't always have the same contents. It's kind of nice that you have such an object-oriented picture embedded in your mind but in this case it is perhaps not serving you so perfectly well. Ultimately, data structures are just arrays of bits at specific addresses...

DigitalRoss