不确定,为什么此代码,同时扫描动态分配的数组导致分段错误

Not sure, why this code, while scanning the dynamically allocated array causing segmentation fault

本文关键字:数组 分段 错误 动态分配 扫描 为什么 代码 不确定      更新时间:2023-10-16

尝试读取动态分配的二维数组。但有分割错误。找不到原因。据我了解,它应该有效

扫描阵列时。 在第一次输入时,它会导致分段错误

class DiognalSum
{
public :
 int **a;
public :
 DiognalSum(int n)
 {
  int **a = new int*[n];
  for(int i = 0; i < n; i++)
  {
   a[i] = new int[n];
  }
 }
public :
   void getArray(int n)
   {
     int input;
     for(int i=0;i<n;i++)
     {
      for(int j=0;j<n;j++)
      {
       cin >> input;
       a[i][j] = input; // segmentation fault is here
      }
     }
   }
   void printArray(int n)
   {
      cout << "Out " << endl;
      for(int i=0;i<n;i++)
     {
      for(int j=0;j<n;j++)
      {
        cout << a[i][j];
      }
        cout << endl;
     }
    }
};
int main()
{
 DiognalSum d(3);
 d.getArray(3);
 d.printArray(3);
return 0;
}
DiognalSum(int n)
 {
  //int **a = new int*[n];  // <-- you have locally declared `int **a`
  a = new int*[n];  // <-- correct would be to use DiognalSum::a
  for(int i = 0; i < n; i++)
  {
   a[i] = new int[n];
  }
 }