简体   繁体   中英

C : reverse array using pointers?

I don't see where I have made an error in this code :

void swap(int* a, int* b)
{
int temp = *a;

*a = *b;
*b = temp;
}

void array_reverse(int *begin, int *end)
{
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end; q += 1)
    { 
        swap(q, end2); 
        end2 -= 1;
    }
}

it should reverse the array:

arr{ 1, 2, 3}

becomes:

arr{ 3, 2, 1}

My output:

[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10] 

becomes :

[111009824,  2,  3,  4,  5,  6,  7,  8,  9, 10]

(well actually this first element always changes each time I compile and test my function and gives me random values I guess )

The issue is with the for loop

void array_reverse(int *begin, int *end)
{
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end; q += 1)
    { 
        swap(q, end2); 
        end2 -= 1;
    }
}

You must change end to end2 in order to stop when you reach the middle You must also decrement end2 before you call swap so you are pointing at the right value

void array_reverse(int *begin, int *end)
{
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end2; q += 1)
    { 
        end2 -= 1;
        swap(q, end2); 

    }
}

The function call would then look something like this

int test[10] = {1,2,3,4,5,6,7,8,9,10};
array_reverse(test, test + 10);

There were two problems. In the for loop, end should have been end2 .

for (q = begin; q < end2; q += 1) {
    swap(q, end2); 
    end2 -= 1; }

The other issue was the call. It should have been array_reverse (a, a+9); because array indexes start at 0 . Giving a+10 for the second argument with an array of length 10 passes a pointer to nonsense outside the array bounds.

I must express some appreciation for the question, it got me researching the fundamental difference between "swapping pointer addresses around" and swapping the "data to which the pointers point.

Something else worth noting is that, in C, function arguments are by-value copies . We could rewrite array_reverse like this with no adverse consequences. Why does this work?

void array_reverse(int *begin, int *end)
    for ( ;begin < end; ) swap(begin++, end--)

The function body receives local copies of arguments to work on. Hence, there is nothing wrong with modifying their values. It is guaranteed that the function can't modify the initial values of its arguments outside the function without simulating a pass by reference through some form of indirection . There is a powerful simplicity to grasping the concept.

Here is another way of writing the loop using while .

void array_reverse(int *first, int *last)
{
    int *f = first;
    int *l = last;
    while (f < l)
    { 
        swap(f, l);
        f++, l--;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM