Reversing an array using pointers

I am having trouble writing a reverse function using 2 pointers to reverse the values in the array. Here is my code.


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
39
40
41
#include <iostream>

using namespace std;

void reverse(double a[], int a_size)
{
	double* p1 = a; 
	double* p2 = a + a_size-1;
	while (p1 < p2) {
		swap(p1,p2);
		p1++;
		p2--;
	}

}

void swap(double* a, double* b)
{
   double t = *a;
    *a = *b;
	*b = t;
}

void printArray(double* a, int a_size)
{
   double* upperEnd = a + a_size;
   for (double *p = a; p < upperEnd; p++)
    cout << *p << " ";
   cout << "\n";
}


int main()
{
   double a[] = {
     0.1,-1.2,2.3,-3.4,4.5,-5.6,6.7,-7.8,8.9,-9.0
   };
   reverse(a, 10);
   printArray(a, 10);
   system("Pause");
}
Last edited on
I haven't read your code, but why not use a vector instead of an array they you can use std::reverse
I was given an array and had to write a reverse function using 2 pointers and a swap function
You can use standard library algorithms on arrays. Just pass the corresponding pointers instead of iterators (the "end()" one is a pointer to one past the last element).

@ashworcp: what's wrong with the above code? You didn't say what you're having trouble with. And please use [ code ] [ /code ] tags.
Last edited on
Sorry... My reverse function is not working. It is just printing the array in order as it is.
Your swap function is probably not being called. You're adding the entire std namespace to the global namespace (using namespace std;). This brings the names "reverse" and "swap" too. Since your swap is declared after its use by your reverse, the compiler knows no swap but the standard library one at that point (line 10).
Last edited on
wow easy fix. Thanks!
Topic archived. No new replies allowed.