0

I am new to C++, please help me about it. Thanks alot.

I wanna pass a (new type array) to a class. but i got message that "c++ terminate called after throwing an instance of bad_alloc" What does that mean? Thanks again!!!!

#include <iostream>

using namespace std;

class test {
  public:
      test (int*, int);
       void check ();
  private :
    int k;
     int *a= new int [k];
//int a;

};


int main()
{
  //int a1=5,n=4;
  int n=4;
  int *a1= new int[n];
   //int a1[4]={1,2,3,4};
  test haha(a1,n);
  haha.check();

    return 0;
}


test::test(int *aa, int kk){
a=aa;
k=kk;
}

void test::check()
{
 for(int i=0; i<k; i++){
    cout<<a<<" ";

 }

}
Sunson29
  • 33
  • 2
  • 6
  • [Alot?](http://i0.kym-cdn.com/photos/images/original/000/176/344/ALOT.png?1316561198) – In more serious news, this code shouldn’t even compile … are you sure that is the *exact* code you are tying to use? – Konrad Rudolph Mar 28 '13 at 16:26
  • How is this even compiling?? – Charles Salvia Mar 28 '13 at 16:27
  • Have you considered using an `std::vector` instead of a manually allocated array? That would also solve your memleak on destruction of `test`. I would also suggest naming your variables a bit more expressive. In regards to your problem: how big of an array did you try to create? `bad_alloc` typically signals out of memory (unless you managed to corrupt your heap or something) – Grizzly Mar 28 '13 at 16:27
  • you may reffer to the similar article, already on Stackoverflow: [Click here][1] [1]: http://stackoverflow.com/questions/9426932/how-do-i-pass-an-array-to-a-constructor – Zeeshan Mar 28 '13 at 16:29
  • 2
    @Konrad Tsk for linking to the image instead of [the article](http://hyperboleandahalf.blogspot.co.uk/2010/04/alot-is-better-than-you-at-everything.html)! – JBentley Mar 28 '13 at 16:30
  • @JBentley I actually didn’t know about this article so thanks for pointing that out. I was just following reddit tradition in linking the picture, really … – Konrad Rudolph Mar 28 '13 at 16:31
  • @JBentley: Tsk for forcing me to google to find what tsk is... oh, typo... Tnx for forcing me to find out what tsk means – David Rodríguez - dribeas Mar 28 '13 at 17:38

5 Answers5

1
class test {
  public:
      test (int*, int);
       void check ();
  private :
    int k;
     int *a= new int [k]; <--- problem, k is undefined + you don't allocate in class declerations
//int a;

};

You cannot allocate in class declerations.. especially not with undefined members :)

besides..you already assign the pointer in the c'tor(not that you give them any value...)

Alon
  • 1,776
  • 13
  • 31
1

These are all the problems with your code, listed in order of appearance. I also provided some tips for you:

  1. In-class initialization of non-static data members are not allowed in pre-C++11 code. Thus this line is invalid:

    private:
    // ...
        int *a = new int [k];
    //         ^^^^^^^^^^^^^^
    

    Not only that, this line is superfluous. You already have a constructor that takes a pointer and you assign that pointer to a. So there's no need for the assignment here inside the class.

  2. Your constructor for test should be defined above main. Also, a tip: you should initialize your members with the member initializer-list. It looks like this in your code:

    test::test(int *aa, int kk) : k(kk), a(aa) {}
    //                          ^^^^^^^^^^^^^^
    

    What follows the colon is the initialization of your members, each separated by a colon.

  3. The following line is printing the address of a k times:

    cout << a << " ";
    

    You don't want to do this. Your printing a hexadecimal number representing the address in memory of what your pointer points to. To print the values to which the pointer points, you must dereference the pointer:

    cout << *a << " ";
    

    Note: You haven't initialized the array with any values so all that will be printed is garbage from the stack. To assign the array some values, you would do it like this (inside main where you declare your array):

    int *a1 = new int[n];
    
    a1[0] = 1;
    a1[1] = 2;
    a1[2] = 3;
    a1[3] = 4
    

    Or, you can use a for loop:

    for (int i = 1; i <= 4; ++i)
    {
        a1[i - 1] = i;
    }
    

    Or, if you're compiling with C++11 (which you're probably not):

    int *a1 = new int[n] {1, 2, 3, 4};
    

    But most importantly, don't forget to delete[] your array when you're finished using it. Anything you create with new/new[] you must delete:

    delete[] a1;
    

    Anyway, you can avoid the memory allocation and confusion by using std::vector (which IMHO is much better):

    #include <vector>
    
    std::vector<int> a1 = {1, 2, 3, 4};
    

    std::vector contains information about its size which makes passing the length of the array unnecessary. Using a vector will simplify your program dramatically.

And with that here is your program:

#include <iostream>
#include <vector>

class test {
  public:
      test(std::vector<int>);
      void check();

   private:
      std::vector<int> v;
};

test::test(std::vector<int> temp) : v(temp) {}

void test::check()
{
   std::vector<int>::const_iterator it;

   for (it = v.begin(); it != v.end(); ++it) {
      std::cout << *it << std::endl;
   }
}

int main()
{
  std::vector<int> a1 = {1, 2, 3, 4};

  test haha(a1);
  haha.check();
}

Live Demo

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253
0
int k;
 int *a= new int [k];

Here's the problem. When creating a class instance, k is uninitialised and you're using it as an array size.

W.B.
  • 5,445
  • 19
  • 29
  • Since I cannot post comments to others. C++11 does allow non-static member initialization. Why is everybody saying it should not compile? – W.B. Mar 28 '13 at 16:32
0

in your class:

 int *a= new int [k];

This will result in error: since k is undefined yet.

error: `test::k' cannot appear in a constant-expression
error: `new' cannot appear in a constant-expression
error: ISO C++ forbids initialization of member `a'
error: making `a' static
error: invalid in-class initialization of static data member of non-integral type `int*' In constructor `test::test(int*, int)':

You should remove = new int[k] from the declaration of *a and initialize *a in the constructor.

taocp
  • 23,276
  • 10
  • 49
  • 62
0

You should probably use std::vector instead of dynamic memory allocation; especially considering that you are not deleting the memory.

std::vector is very easy to use and there is plenty of documentation available. See http://en.cppreference.com/w/cpp/container/vector

Example

std::vector<int> qux;

qux.push_back(6);

void foo(std::vector<int>& bah)
{

}

If you must pass an array around, you would want to, at the very least, use std::array, see http://en.cppreference.com/w/cpp/container/array

Errors

std::bad_alloc is an exception that is thrown when your new operator fails

If you don't want to have new throw that exception, you can use std::nothrow, see http://en.cppreference.com/w/cpp/memory/new/nothrow

The reason you're receiving this is because you are passing an uninitialised variable around

ed_me
  • 3,338
  • 2
  • 24
  • 34