Using pointers as a function to reverse an array

This is what I currently have, the assignment is to reverse an array. We are learning pointers and are required to use them in this assignment, although personally i do not see the use for them, what I currently have shows everything that the program is asking. So can someone help me out with using pointers in general through a function and why it would be necessary? (I'm sure it is, i just cannot understand why as of yet.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>
using namespace std;
void showArray (int[], int);
void reverseArray(int[], int);
 
int main ()
{
    const int SIZE = 10;
    int values[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   
    cout << "Original " << endl;
    showArray(values, SIZE);
    cout << endl;
    cout << "Reversed " << endl;
     reverseArray(values, SIZE);
 
     
    return 0;
}
 
void showArray(int values[], int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << values[i] << endl;
    }
 
}
 
void reverseArray (int values[], int size) // I know right here I will have to change to an int *
{
    for (int i = (size - 1); i >= 0; i--)
    {
        cout << values[i] << endl;
    }
 
}
I don't think you have to have any pointers as parameters to a function, just that you need to use pointers to reverse an array. And in fact, its very intuitive and simple once you see the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
void reverseArray(int values[], int SIZE)
{
    int* p1 = &values[0];      // set a pointer to beginning of array
    int* p2 = &values[SIZE-1]; // set a pointer to end of array

    while(p1 <= p2) // while they HAVE NOT crossed over
    {
        swap(*p1, *p2); // swap the values pointed to by p1 and p2

        p1++; // move forward p1 by 1
        p2--; // move back p2 by 1
    }
}


I hope the code above is easy to understand.

You will call this function from main. Then (in main) you will call your showArray() function which should print the array in reverse.
Last edited on
Thanks you so much, I spent too much extra time on this assignment practicing and searching tutorials. It does make sense and is understandable, I got it working. I will say that I think he did in fact throw it in his notes that it should use a function header, int *reverseArray(int arr[], int size). But at this point I will use void for the meantime and ask in person.
Topic archived. No new replies allowed.