'new'不会将内存分配给作为类的数据成员的指针

问题描述 投票:-1回答:2

我已经声明了一个指针,用于保存动态2D数组,并在类构造函数中使用“new”为其分配内存,但在使用if语句检查时,它总是等于nullptr。代码如下:

class A
 {
  private:

  int* a;
  int d1, d2;

  public:

  A()
  {
    a = new int [5 * 5];
    cout << a; //this prints a address
    this->d1 = 5;
    this->d1 = 5;
  }

  void chk()
  {
   if(a == nullptr)
    {cerr << "a has gone wild";} // this if condition is true always

   else
     {
       for(int i = 0; i < d1; i++)
         {
           for(int j = 0; j < d2; j++)
            {
             a[i * d2 + j] = 10; //some random value
            }
         }

     }

  }

};

当我做同样的事情,即在main()中使用new而不使用类为指针赋值时,它可以正常工作。

请告诉我错过了什么,我哪里出错了。

c++ pointers multidimensional-array new-operator nullptr
2个回答
-1
投票

你的代码有一些小问题,但总的来说还可以:

 1  #include <cstdio>
 2  #include <cstdlib>
 3  #include <iostream>
 4
 5  using namespace std;
 6
 7  class A
 8  {
 9  private:
10      int*    a;
11      int     d1, d2;
12
13  public:
14      A()
15      {
16          a           = new int[5 * 5];
17          cout << (void*)a << endl; // this prints a address
18          d1    = 5;
19          d2    = 5;
20      }
21
22      void    chk()
23      {
24          if( a == nullptr )
25          {
26              cout << "a has gone wild\n";
27          } // this if condition is true always
28          else
29          {
30              cout << "a was ok\n";
31              for( int i = 0; i < d1; i++ )
32              {
33                  for( int j = 0; j < d2; j++ )
34                  {
35                      a[i * d2 + j] = 10; // some random value
36                  }
37              }
38          }
39      }
40  };
41
42  int    main( void )
43  {
44      A a;
45      a.chk();
46
47      return 0;
48  }

运行时的输出:

<44680> ./test
0x16d7c20
a was ok

-2
投票

首先考虑如何制作2D数组:如果要制作静态2D数组,只需使用,

int arr[5][5];

如果要制作动态2D数组,

int** arr=new int*[5];
for(int k=0; k<i; k++)
arr[k]=new int [5];

还检查你在这做什么this->d1=5 this->d1=5

© www.soinside.com 2019 - 2024. All rights reserved.