0

ダブルポインターを受け入れる関数間で、ヒープで宣言された2次元配列を渡すと、プログラムがハングしてクラッシュする理由を特定できません。

2次元配列を宣言するために選択した方法に関係があると強く感じています。配列を割り当てる関数を作成する前は、プログラムは関数に渡されたときに配列内のデータを操作できました。

したがって、ここに割り当て関数と、内部でクラッシュする関数があります。

void matrix_malloc(int **matrix, int m, int n);
void matrix_init(int **matrix, int m, int n);

int main(void)
{
  int **matrix;
  int m(3), n(2);

  matrix_malloc(matrix, m, n);
  matrix_init(matrix, m, n); // runtime error
}

void matrix_malloc(int **matrix, int m, int n)
{ // get heap memory
  int i;
  matrix = new int*[m];
  for(i = 0; i < m; i++)
  {
    matrix[i] = new int[n];
  }
}

void matrix_init(int **matrix, int m, int n)
{ // randomize matrix
  int i, j;
  for(i = 0; i < m; i++)
  {
    for(j = 0; j < n; j++)
    {
      matrix[i][j] = rand() % 10 + 1;
    }
  }
}
4

4 に答える 4

1

2D 配列の割り当ては問題ありません。しかし。

  int **matrix;
  int m(3), n(2);

  matrix_malloc(matrix, m, n);

ここでは、行列は変更されません。その値をコピーして関数に渡します。つまり、次のとおりです。

  int **matrix = NULL; // matrix points to null
  int m(3), n(2);

  matrix_malloc(matrix, m, n); // copy the value contained in matrix and give it to the function
  //matrix still points to null

複数のソリューションがあります:

  • マトリックス malloc は int** を返すことができ、単に matrix = matrix_malloc(m, n) と書く必要があります。
  • マトリックス malloc は int** へのポインターを取ることができます (int*** - 慎重に処理してください)
  • 他の回答で述べたように、 int** への参照

int*** を使用した matrix_malloc は次のようになります。

//call it as follows:
matrix_malloc(&matrix, m, n);


void matrix_malloc(int ***matrix, int m, int n)
{
  // matrix contains the address of the original variable, so *matrix is the original variable itself.
  int i;
  *matrix = new int*[m];
  for(i = 0; i < m; i++)
  {
    (*matrix)[i] = new int[n];
  }
}
于 2013-04-09T06:35:32.287 に答える