I have:
class first{
private:
int *array;
public:
first(int x){
array = new int[x][10];
}
I want to call this class by:
first class1 = new first(10);
Why it doesn't work ? How to inintialize array by size from constructor ??
-
2In what way does it not work? Does it crash? Where? Does it not compile? What is the error you get? What happened vs. what did you expect? Details please.i_am_jorf– i_am_jorf2012年01月06日 19:13:28 +00:00Commented Jan 6, 2012 at 19:13
-
error: cannot convert 'int ()[10]' to 'int' in assignment. How to inintialize 2dimension array by size from constructor ?? I don't want to use vectors.makeNicePlusOne– makeNicePlusOne2012年01月06日 20:41:19 +00:00Commented Jan 6, 2012 at 20:41
2 Answers 2
Just this is enough:
first class1(10);
new is for when you're allocating a pointer.
first *class1 = new first(10);
Furthermore, you have an incompatibility here:
array = new int[x][10];
array is an int*, but new int[x][10] is a 2D array. I'm not sure which one you want.
For the 1D array:
int *array;
array = new int[x];
For the 2D array:
int (*array)[10];
array = new int[x][10];
That said, you might be better off using std::vector.
Side Note: Since you have memory allocation in the constructor, you should also implement a destructor, copy-constructor, and copy-assignment operator.
3 Comments
std::vector.vector<vector<int> > array; unless you have a very good reason not to.You've indicate that you want a one-dimensional array (int*) but attempted to allocate a two-dimensional array (new [x][10]).
I'll assume you need one dimension.
The C++ way to do this is with vector.
#include <vector>
class first{
private:
std::vector<int> array;
public:
explicit first(int x) : array(x) {
}
};