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;
}
Timmy O'Mahony
54.1k19 gold badges160 silver badges182 bronze badges
asked May 3, 2012 at 23:18
Antarr Byrd
26.4k33 gold badges113 silver badges203 bronze badges
2 Answers 2
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>.
answered May 3, 2012 at 23:19
James Custer
8476 silver badges12 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Antarr Byrd
for pointer = b it throws cannot convert from 'int *[]' to 'int *'
Antarr Byrd
i'm not allowed to use vectors...class assignment
James Custer
@atbyrd In that case, keep them in mind for the future. I added a bit to my answer.
Ed Swangren
@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;Use vectors - lot easier to use
answered May 3, 2012 at 23:20
Ed Heal
60.4k18 gold badges92 silver badges137 bronze badges
7 Comments
Ed Swangren
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).
Ed Heal
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.
Ed Swangren
Ok, I just don't think this is a useful answer for a beginner.
Ed Heal
@EdS. - I did give a link to the appropriate web site so that person can learn STL.
lesderid
Very true, but this should be a comment (which someone else already posted), not an answer.
|
lang-cpp
std::vector<int>