'I'm trying to write a program that reverses an array and it keeps saying I can not convert int * to int. How do I fix that? [closed]

int* reverse_Array(int size, int* arr)
{
    int* areverse[10];

    int s = 0;

    for (int c = 10; c > 0; c--)

        arr[c] = areverse[s]; // the issue happens here with the =

    return areverse[s];
}

The issue happens with the = between arr[c] and areverse[s]

I tried a couple fixes but each one doesn't really fix it.

I am writing code that should reverse a array "(using a function by returning a pointer/array)"

c++


Solution 1:[1]

If you're "allowed" to use vectors, you can use a simple example like this.

#include <vector>
#include <algorithm>

template<typename T>
std::vector<T> reverse_array(const std::vector<T>& array)
{
    std::vector<T> t = array;
    std::reverse(array.begin(), array.end());
    return t;
}

Solution 2:[2]

@MattaGodus when we are starting error occurs.I have mentioned out the problems and the and way to fix them.

Problems in the code:

  1. int* areverse[10];

should be :

int * areverse = new int[size];//what ever the size it

Problem with this line int* areverse[10] is when the function returns stack area is cleared.

Using the new keyword we are creating variable inside of heap now even our function returns this area remains.

  1. arr[c] = areverse[s];

we should be assigning areverse from arr

  1. return areverse[s];

It should be:

return areverse;

Code with bug fixed:

#include <iostream>
using namespace std;

int *reverse_Array(int , int*);


////////Reverses an array of integer//////////
int* reverse_Array(int size, int* arr){

    int * areverse = new int[size];//use new keyword to allocated new memory inside method 
    for (int c = size -1 ; c >= 0; c--)
        areverse[size-1 -c] = arr[c]; // the issue happens here with the =

    return areverse;
}

////////Main////////
int main(){
    int arr[] = {1, 2, 3, 4};
    int size = sizeof(arr) / sizeof(int);
    int * rarr = reverse_Array(size, arr);
    for (int i = 0;i<size; i++)
        cout<<rarr[i]<<" ";
    cout<<endl;
    return 0;
}

output:

$ g++ main.cpp && ./a.out 
4 3 2 1 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lightning
Solution 2