0

I can't seem to solve this exercise my professor gave me. So I'm suppose to use pointers in this exercise to reverse the order of the original array.

Here is what I made so far.

#include <stdio.h>
#define SIZE 10

void reverse(int *a, int size);

int main(void){
    int array[SIZE]={1,2,3,4,5,6,7,8,9,10};
    int i;

    printf("The original order is:\n");

    for (i=0; i<SIZE; i++){
        printf("%5d", array[i]);
    }

    reverse(array, SIZE);

    printf("\nThe reverse order is:\n");

    for (i=0; i<SIZE; i++){
        printf("%5d", array[i]);
    }

    return 0;
}

void reverse(int *a, int size){
    int j;
    int hold;

    for(j=0; j<size-1; j++){
        hold = a[j];
        a[j] = a[size-1-j];
        a[size-1-j] = hold;
    }
}
FrancisDoy
  • 81
  • 1
  • 6
  • There are no pointers yet! Look at "Swapping pointers in C": http://stackoverflow.com/questions/8403447/swapping-pointers-in-c-char-int – asimes Jan 15 '15 at 06:52

2 Answers2

1

In the reverse function, you did swap the value, but you swap them back again!

Try this:

void reverse(int *a, int size){
    int j;
    int hold;

    for(j=0; j<size/2; j++){
        hold = a[j];
        a[j] = a[size-1-j];
        a[size-1-j] = hold;
    }
}
justmscs
  • 756
  • 4
  • 12
0

Running the algorithm from 0..N will swap first element 0 with N, and then the element N back with element 0. To fix it, use

for (j=0; j<size/2; j++)
Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57