Search code examples
carrayspointersreverse

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 )


Solution

  • 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);