2

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

2
  • 2
    In 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. Commented 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. Commented Jan 6, 2012 at 20:41

2 Answers 2

4

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.

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

3 Comments

...and a copy-assignment operator (per the Rule of Three). But unless you particularly want to make things hard for yourself, use std::vector.
I want to initialize 2dimension array by walue from constructor. object shouldn't be an pointer. Vectors are quite another thing. How to do this ?
Answer updated. Multi-dimension arrays can get very ugly. So I suggest you use vector<vector<int> > array; unless you have a very good reason not to.
2

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) {
   }
};

1 Comment

I don't need vector type. I'm interested only in array's.

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.