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



我已经声明了一个指针来保存动态 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 为指针赋值而不使用类,它工作正常。

请建议我错过了什么,我哪里出错了。

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

 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 wildn";
27          } // this if condition is true always
28          else
29          {
30              cout << "a was okn";
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

首先考虑如何制作 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

最新更新