3

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;
}
1
  • 4
    You are asking for a memory leak even if you fix the allocation and swapping of values. Instead consider using std::vector<int> Commented May 3, 2012 at 23:23

2 Answers 2

9

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>.

Sign up to request clarification or add additional context in comments.

4 Comments

for pointer = b it throws cannot convert from 'int *[]' to 'int *'
i'm not allowed to use vectors...class assignment
@atbyrd In that case, keep them in mind for the future. I added a bit to my answer.
@atbyrd: You didn't read carefully. You wrote int *b[], which is an array of pointers to int. new returns a pointer! You need to declare b as int *b;
0

Use vectors - lot easier to use

7 Comments

Ok, but this doesn't help a beginner understand anything, so -1. Understanding concepts is far more useful than being told to use a library (of course, he should use a vector, but that is tangential to the problem at hand).
I cannot put verbatim into the library. Just would not like to put that person that that person can achieve a lot more by using a library. I would have not quarrel or contempt if they want to ask any question.
Ok, I just don't think this is a useful answer for a beginner.
@EdS. - I did give a link to the appropriate web site so that person can learn STL.
Very true, but this should be a comment (which someone else already posted), not an answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.