CAnt get the array to reverse

Any hints on how I can reverse this array, ive tried everything I can think of

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
42
43
44
45
46
47
  #include <iostream>
using namespace std;


int* revSize (int*, int);

int main()
{
	const int size = 5;										
	int arr [size] = {1, 2, 3, 4, 5};				
	int* ptr = arr;													

	for(int index= 0;index<size;index++)
		cout<<ptr[index]<<endl;
		cout << endl;
	

	ptr = revSize(arr, size);	//Used to assign num to the memory location of the return

	for(int i=5;i<0;i--)
	{

		cout<<ptr[i]<<endl;
	}

	delete[] ptr;	
	ptr = NULL;		

	system("PAUSE");
	return 0;
}

int* revSize(int* arr1, int size)
{

int* revArray=new int[size * 1];



for (int i=0;i<size;i++)
revArray[i]=arr1[i];

for (int i=size;i>size*1;i++)
	revArray[i]=arr1[i];

return revArray;
}
I don't know why you're using new.

The following shows how you would use std::reverse to do it, and how you might write your own version of std::reverse.

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
42
43
44
#include <cstddef>
#include <iostream>
#include <algorithm>
#include <string>

template <typename iter>
void print(iter begin, iter end, const std::string& separator = " ", const std::string& terminator = "\n", std::ostream& os = std::cout)
{
    while (begin != end)
    {
        os << *begin++ ;

        if (begin != end)
            os << separator;
    }

    os << terminator;
}

void myreverse(int* beg, int* end)
{
    using std::swap;

    if (beg && end && beg < --end)
        while (beg < end)
            swap(*beg++, *end--);
}

int main()
{
    const std::size_t size = 5;
    int arr[size] = { 1, 2, 3, 4, 5 };

    int* arr_beg = arr;
    int* arr_end = arr + size;

    print(arr_beg, arr_end, ", ");

    std::reverse(arr_beg, arr_end);
    print(arr_beg, arr_end, ", ");

    myreverse(arr_beg, arr_end);
    print(arr_beg, arr_end, ", ");
}


http://ideone.com/DpFU45
Last edited on
1
2
3
4
5
for(int i=5;i<0;i--)
	{

		cout<<ptr[i]<<endl;
	}


should that not be

1
2
3
4
5
for(int i=4;i>=0;i--)
	{

		cout<<ptr[i]<<endl;
	}
Wow I did not notice that ty very much really appreciate it
Topic archived. No new replies allowed.