c++ - 不确定,为什么这段代码在扫描动态分配的数组时导致段错误

标签 c++ arrays dynamic-arrays

正在尝试读取动态分配的二维数组。 但有段错误。找不到原因。据我了解,它应该可以工作

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

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];
  }
 }

关于c++ - 不确定,为什么这段代码在扫描动态分配的数组时导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41737064/

相关文章:

javascript - 修改嵌套的 redux 状态而不发生变异

c++ - 如何将一个类别的对象分组为另一个类别中的对象数组?

c++ - 错误 C2661 : 'CObject::operator new' : no overloaded function takes 4 arguments

arrays - Scala:将 csv 字符串转换为数组

java - 返回二维数组 java.lang.Object 中任意对象的索引。

arrays - Pascal/Delphi 动态数组作为参数

c++ - 从 C++ 程序刻录 CD/DVD

c++ - 为什么在这段代码中隐式类型转换的结果不正确?

php - 如何使用 MySQLi 获取单列值?

Excel VBA - 如何添加动态数组公式