簡體   English   中英

不確定為什么在掃描動態分配的數組時會導致分段錯誤的這段代碼

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

嘗試讀取動態分配的二維數組。 但存在細分錯誤。 無法找出原因。 據我了解,它應該工作

在掃描陣列時。 在第一個輸入上,它會導致分段錯誤

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM