How to reverse the elements of an array using two pointers

Aug 22, 2020 at 7:38pm

}[/code]
Last edited on Aug 24, 2020 at 3:20am
Aug 22, 2020 at 8:05pm
https://www.geeksforgeeks.org/program-reverse-array-using-pointers/

Also, PLEASE learn to use code tags when posting source code, they make it MUCH easier to read and comment on the code.

http://www.cplusplus.com/articles/jEywvCM9/

HINT: you can edit your post and add code tags.
Aug 22, 2020 at 8:08pm
1
2
3
4
5
6
7
8
9
10
11
12
void my_swap(double* x, double* y)
{ 
  double temporary = *x; 
  *x = *y;
  *y = temporary;  
}

void reverse(double begin[], int size)
{
  for (double* end = begin + size; end > begin; )
    my_swap(begin++, --end); 
} 

Last edited on Aug 22, 2020 at 8:09pm
Aug 22, 2020 at 8:14pm
You have a for loop inside a while loop. They are both trying to do the reversing. You only need one of them.

Show ALL code (so that we can run it) and put it in CODE TAGS (so that we can run it without downloading it, as well as seeing the code structure from your indentation ...)
Aug 22, 2020 at 8:18pm
@Furry Guy Thanks lots, it was my first post i wasnt sure how to do it, i fixed it :)

Also i looked at that website link and i still get the same wrong output

Array in order : 11,12,13,14,15  Reversed array : 15,14,13,12,15
Aug 22, 2020 at 8:23pm
Okay here is my code :

1
2
3
4
5
6
7
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>


Last edited on Aug 24, 2020 at 3:20am
Aug 22, 2020 at 8:37pm
Remove the spurious uncommented line (59) and it runs OK and appears to produce the correct answer.

Enter the size of the array : 7
After initializing 
13.000        0x756fc0 
16.000        0x756fc8 
27.000        0x756fd0 
25.000        0x756fd8 
23.000        0x756fe0 
25.000        0x756fe8 
16.000        0x756ff0 
After reversing 
16.000        0x756fc0 
25.000        0x756fc8 
23.000        0x756fd0 
25.000        0x756fd8 
27.000        0x756fe0 
16.000        0x756fe8 
13.000        0x756ff0 



You need a call to srand() somewhere, or you'll always get the same array.


You can also do it with
1
2
3
4
5
6
7
8
9
void reverse( double *first, double *last )
{
	while ( first < last )
	{
		double comp = *first;
		*first++ = *last;
		*last-- = comp;
	}
}

called by
reverse(p_arr, p_arr + size_arr - 1 );
Last edited on Aug 22, 2020 at 8:47pm
Aug 23, 2020 at 3:38am
Same stuff:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void swap(double* p, double* q)
{
    double temp = *p;
    *p = *q;
    *q = temp;
}

void reverse(double a[], int size)
{
    double* x = a;
    double* y = a + size - 1;
    
    while(x < y)
    {
        swap(x, y);
        x++;
        y--;
    }
}
Topic archived. No new replies allowed.