Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error when defining array

Im trying to declare an array in C++ but i keep getting this error.

error C2440: 'initializing' : cannot convert from 'int *' to 'int []'

for this line

int b[] = new int[elements]; 

Full Code

int* reverseArray (int a[] ,int elements)
{
    int *pointer;
    int x= elements-1;
    int b[] = new int[elements];
    pointer=b[];
    for (int i= 0; i < elements; i++)
    {
        b[i] = a[x--];
    }
    return pointer;
}
like image 447
Antarr Byrd Avatar asked Apr 23 '26 11:04

Antarr Byrd


1 Answers

new returns a pointer, so you should change

int b[] = new int[elements];

to

int* b = new int[elements];

and you should just remove pointer and simply return b, so

int* reverseArray (int a[] ,int elements)
{
  int x = elements-1;
  int* b = new int[elements];
  for (int i = 0; i < elements; ++i)
    b[i] = a[x--];
  return b;
}

But you should really consider using std::vector. If you use a std::vector, to reverse the array, you can simply use std::reverse from <algorithm>.

like image 54
James Custer Avatar answered Apr 24 '26 23:04

James Custer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!