Home c++ When creating a dynamic array Critical error detected c0000374 C++

When creating a dynamic array Critical error detected c0000374 C++

Author

Date

Category

There was a problem initializing a dynamic array

The problem occurs in the lines:

int n;
int * arr = new int [n];

Because n is not equal to a specific number. How to fix? There are no access violations and no syntax violations. And why did this problem occur?

Here’s the whole code:

class Base
{
  virtual void Norma () = 0;
};
  class Vector: public Base
  {
    private:
      int n;
      int * arr = new int [n];
    public:
      Vector () {}
      ~ Vector () {}
      void InputVector ()
      {
        cout & lt; & lt; "Input n:";
        cin & gt; & gt; n;
        for (int i = 0; i & lt; n; i ++)
        {
          // arr [i] = rand ()% 10;
          cin & gt; & gt; arr [i];
        }
      }
      void Norma ()
      {
        int max = arr [0];
        for (int i = 0; i & lt; n; i ++)
        {
          if (arr [i] & gt; max)
          {
            max = arr [i];
          }
        }
        cout & lt; & lt; "Vector Norma is:" & lt; & lt; fabs (max);
      }
      void OutVector ()
      {
        for (int i = 0; i & lt; n; i ++)
        {
          cout & lt; & lt; arr [i] & lt; & lt; "";
        }
      }
  };
  int main ()
{
  Vector vec;
  vec.InputVector ();
  vec.Norma ();
  vec.OutVector ();
  system ("pause");
  return 0;
}

Answer 1, authority 100%

Quite often I come across code like this on SO:

int n;
int * arr = new int [n];

For some reason, beginners think that new int [n] magically associates n with the size of the array, so later, changing n , you can stretch and shrink the array. This is not true. After calling new int [n] , the size of the array remains fixed.

So you need to get n first, and only then do new .

Solution: int * arr = new int [n]; replace with just int * arr; , and after cin & gt; & gt; n; put arr = new int [n]; .


Also, note: Memory leaks from your class like a sieve! The destructor is missing delete [] , and is missing a copy constructor and an assignment operator.

I advise you to read: the rule of three ( the rule of three ).


Answer 2, authority 100%

And what is your n equal to when creating an object, did you try to output it? I’m sure it’s some kind of rubbish. It is more logical to set this number in the constructor or initialize it after creating an instance of the class. You allocate memory for an indefinite number of elements, and only then set this number.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions