簡體   English   中英

獲取怪異的輸出以動態分配2d數組。 我該如何解決該問題?

[英]Getting weird output for dynamic allocation of the 2d array. How can I resolve the issue?

我想創建一個動態2D數組,並要對其執行操作。 但是,當我打印矩陣時,第一列顯示不同的數字,並且不知道它來自哪里?

我試圖將array[i][j]更改為*(*(array+i)+j) ,但仍然得到相同的結果。

int main ()
{
  int sum=0,diagsum=0;
  int rowSize,colSize;
  std::cout << "Input Row size of the matrix" << '\n';
  std::cin >> rowSize;
  std::cout << "Input Column size of the matrix" << '\n';
  std::cin >> colSize;

  int** arrayA = new int*[rowSize];   //declaring array dynamically.

  for(int m=0;m<rowSize;++m)
  {
    arrayA[m] = new int[colSize];
  }

  //Creating matrix A of size rowSize x colSize with random of first 30
  for(int i = 0;i<rowSize;++i)
  {
    for(int j = 1;j<=colSize;++j)
    {
      arrayA[i][j]=rand() % 30;
    }
  }


  std::cout << "Matrix A is of size"<< rowSize << " X " << colSize << '\n';

  //printing Matrix A
  for(int i = 0;i<rowSize;++i)
  {
    for(int j = 0;j<=colSize;++j)
    {
      std::cout << arrayA[i][j] << "\t";
    }
    std::cout << '\n';
  }

  //sum of element of the matrix
  for(int i = 0;i<rowSize;i++)
  {
    for(int j=0;j<colSize;j++)
    {
      sum = sum + arrayA[i][j];
    }
    std::cout << '\n';
  }

  // sum of elet of diagonal of matirx
  for(int i = 0;i<rowSize;i++)
  {
      diagsum = diagsum + arrayA[i][i];
  }

  std::cout << "sum of the element of matrix is"<< sum << '\n';

  std::cout << "Diagonal sum is" << diagsum <<'\n';


//deleting mem for the array.
  for(int m=0;m<1000;m++)
  {
    delete[] arrayA[m];
  }

  delete[] arrayA;

  return 0;
}

實際結果:

Input Row size of the matrix
5
Input Column size of the matrix
5
Matrix A is of size5 X 5
9140960 11      17      4       10      29
9140960 4       18      18      22      14
9140960 5       5       1       27      1
9140960 11      25      2       27      6
9115176 21      24      2       3       22

sum of the element of matrix is45679273
Diagonal sum is9140974

===================================

預期結果:

Input Row size of the matrix
5
Input Column size of the matrix
5
Matrix A is of size5 X 5
11      17      4       10      29
4       18      18      22      14
5       5       1       27      1
11      25      2       27      6
21      24      2       3       22

for(int j = 1;j<=colSize;++j)地方應該是for(int j = 0; j < colSize;++j) 您擁有的所有位置<= colSize應該為< colSize 如果m<1000 ,則應為m < rowSize ,例如

#include <iostream>

int main (void)
{
    int sum=0,diagsum=0;
    int rowSize,colSize;
    std::cout << "Input Row size of the matrix" << '\n';
    std::cin >> rowSize;
    std::cout << "Input Column size of the matrix" << '\n';
    std::cin >> colSize;

    int** arrayA = new int*[rowSize];   //declaring array dynamically.

    for(int m=0;m<rowSize;++m)
    {
        arrayA[m] = new int[colSize];
    }

    //Creating matrix A of size rowSize x colSize with random of first 30
    for(int i = 0; i < rowSize; ++i)
    {
        for(int j = 0; j < colSize; ++j)
        {
            arrayA[i][j]=rand() % 30;
        }
    }


    std::cout << "Matrix A is of size"<< rowSize << " X " << colSize << '\n';

    //printing Matrix A
    for(int i = 0;i < rowSize; ++i)
    {
        for(int j = 0; j < colSize; ++j)
        {
            std::cout << arrayA[i][j] << "\t";
        }
        std::cout << '\n';
    }

    //sum of element of the matrix
    for(int i = 0; i < rowSize; i++)
    {
        for(int j = 0; j < colSize; j++)
        {
            sum = sum + arrayA[i][j];
        }
        std::cout << '\n';
    }

    // sum of elet of diagonal of matirx
    for(int i = 0; i < rowSize; i++)
    {
        diagsum = diagsum + arrayA[i][i];
    }

    std::cout << "sum of the element of matrix is"<< sum << '\n';

    std::cout << "Diagonal sum is" << diagsum <<'\n';


    //deleting mem for the array.
    for(int m = 0; m < rowSize; m++)
    {
        delete[] arrayA[m];
    }

    delete[] arrayA;

    return 0;
}

請注意:如果您將循環聲明的間隔增加一些,則錯誤將更容易發現。並且與++jj++

還請注意:您可以通過檢查if (i == j) diagsum += arrayA[i][j]; diagsum在一個循環中收集sumdiagsum if (i == j) diagsum += arrayA[i][j];

您還應該驗證用戶輸入,例如

    if (!(std::cin >> rowSize)) {
        std::cerr << "error: invalid rowSize\n";
        return 1;
    }

否則,您將遠離未定義行為,只是您的鍵盤滑脫。

使用/輸出示例

$ ./bin/array_dyn_rand
Input Row size of the matrix
5
Input Column size of the matrix
5
Matrix A is of size5 X 5
13      16      27      25      23
25      16      12      9       1
2       7       20      19      23
16      0       6       22      16
11      8       27      9       2





sum of the element of matrix is355
Diagonal sum is73

您應該刪除std::cout << '\\n'; 從循環中計算sum是完全沒有必要的。

由於您使用的是C stdlib.h rand() ,因此您必須在第一次調用rand()之前通過調用srand()來播種隨機數生成器,通常使用從紀元開始的秒數進行初始化,例如

#include <ctime>
...
    srand (time(NULL));     /* seed the random number generator */

注意: C ++提供了它自己的偽隨機數生成例程)

只需對代碼進行一些整理以提高可讀性,並將sumdiagsum計算合並到一個循環中,則可以執行以下操作:

#include <iostream>
#include <ctime>

int main (void)
{
    int sum=0,
        diagsum=0,
        rowSize,
        colSize;

    std::cout << "Input Row size of the matrix: ";
    if (!(std::cin >> rowSize)) {       /* validate EVERY user-input */
        std::cerr << "error: invalid rowSize\n";
        return 1;
    }
    std::cout << "Input Col size of the matrix: ";
    if (!(std::cin >> colSize)) {
        std::cerr << "error: invalid colSize\n";
        return 1;
    }

    srand (time(NULL));     /* seed the random number generator */

    int **arrayA = new int* [rowSize];  /* allocate rowSize pointers */

    for(int m = 0;m < rowSize; m++)     /* allocate colSize ints per-row */
        arrayA[m] = new int[colSize];

    /* Populate rowSize rows x colSize columns with random 0 - 29 */
    for (int i = 0; i < rowSize; i++)
        for (int j = 0; j < colSize; j++)
            arrayA[i][j]=rand() % 30;


    std::cout << "\nMatrix A is of size " << rowSize << " x " << colSize 
                << "\n\n";

    // printing Matrix A
    for (int i = 0; i < rowSize; i++) {
        for (int j = 0; j < colSize; j++)
            std::cout << arrayA[i][j] << "\t";
        std::cout << '\n';
    }

    // sum of elements and diagonal of the matrix
    for (int i = 0; i < rowSize; i++) {
        for(int j = 0; j < colSize; j++) {
            if (i == j)
                diagsum += arrayA[i][j];
            sum = sum + arrayA[i][j];
        }
    }

    std::cout << "\nsum of the element of matrix is: "<< sum << '\n'
                << "Diagonal sum is: " << diagsum <<'\n';

    // deleting mem for the array.
    for (int m = 0; m < rowSize; m++)
        delete[] arrayA[m];             /* delete storage for rows */
    delete[] arrayA;                    /* delete pointers */

    return 0;
}

修改后的使用/輸出

$ ./bin/array_dyn_rand
Input Row size of the matrix: 5
Input Col size of the matrix: 5

Matrix A is of size 5 x 5

24      8       16      5       15
15      13      24      24      11
16      26      11      12      26
20      9       22      9       22
19      3       3       13      0

sum of the element of matrix is: 366
Diagonal sum is: 57

如果您還有其他問題,請告訴我。

暫無
暫無

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

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