2

行列乗算のプログラムを作成しましたが、それを変更したいと考えています。まず、行列を 10 ではなく first[a][b] に変更し、ファイルから行列の次元を読み取ります。malloc を使用して行列の次元に応じて動的にメモリを割り当てる必要がありますか、それとも最大値を取ることができますが、大量のメモリの浪費につながる ファイルから配列に行列の次元を格納する必要がありますか。必要な変更を提案してください。file を開いているのではなく、標準入力をファイルにリダイレクトしているだけです。ファイル経由で入力を取得できません??

変更されたコードは次のとおりです

#include <stdio.h>

int main() 
{
 int m, n, p, q, c, d, k, sum = 0;
  int **first, **second, **multiply;
  printf("Enter the number of rows and columns of first matrix\n");
  scanf("%d%d", &m, &n);
  first = malloc(m*sizeof(int*));
   for (int i =0;i <m; i++)
first[i] =malloc(n*sizeof(int));
    second = malloc(p*sizeof(int*));
     for(int i=0;i<p;i++)
second[i] = malloc(q*sizeof(int));
multiply = malloc(m*sizeof(int));
for (int i=0;i<q;i++)
multiply[i] = malloc(q*sizeof(int));
printf("Enter the elements of first matrix\n");
    for (  c = 0 ; c < m ; c++ )
    for ( d = 0 ; d < n ; d++ )
      scanf("%d", &first[c][d]);
    printf("Enter the number of rows and columns of second matrix\n");
  scanf("%d%d", &p, &q);
  if ( n != p )
    printf(
  "Matrices with entered orders can't be multiplied with each other.\n");
  else {
 printf("Enter the elements of second matrix\n");
 for ( c = 0 ; c < p ; c++ )
  for ( d = 0 ; d < q ; d++ )
    scanf("%d", &second[c][d]);
 for ( c = 0 ; c < m ; c++ ) {
  for ( d = 0 ; d < q ; d++ ) {
    for ( k = 0 ; k < p ; k++ ) {
      sum = sum + first[c][k]*second[k][d];
    }
    multiply[c][d] = sum;
    sum = 0;
  }
  }
 printf("Product of entered matrices:-\n");
 for ( c = 0 ; c < m ; c++ ) {
  for ( d = 0 ; d < q ; d++ )
    printf("%d\t", multiply[c][d]);
  printf("\n");
 }
for (int i = 0; i < p; i++)
  free(second[i]);
free(second);
for (int i = 0; i < q; i++)
  free(multiply[i]);
  free(multiply);
}
for (int i = 0; i < m; i++)
free(first[i]);
 free(first);
return 0;
 }
4

1 に答える 1

4

宣言の変更:

int i, m, n, p, q, c, d, k, sum = 0;
int **first, **second, **multiply;

scanf("%d%d", &m, &n);

first = malloc(m*sizeof(int*));
for (i = 0; i < m; i++)
  first[i] = malloc(n*sizeof(int));

printf("Enter the elements of second matrix\n");

second = malloc(p*sizeof(int*));
for (i = 0; i < p; i++)
  second[i] = malloc(q*sizeof(int));

multiply = malloc(m*sizeof(int*));
for (i = 0; i < q; i++)
  multiply[i] = malloc(q*sizeof(int));

自由な声明:(プログラムの最後に)(プログラムがすぐに終了しない場合は常に必要です)

交換:

  }
  return 0;
}

と:

    for (i = 0; i < p; i++)
      free(second[i]);
    free(second);
    for (i = 0; i < q; i++)
      free(multiply[i]);
    free(multiply);
  }
  for (i = 0; i < m; i++)
    free(first[i]);
  free(first);
  return 0;
}

別のアプローチ:メモリのシーケンシャルブロックを割り当てる

宣言:

int *first, *second, *multiply;

malloc:(forループなし)

  • first = malloc(m*n*sizeof(int));
  • second = malloc(p*q*sizeof(int));
  • multiply = malloc(m*q*sizeof(int));

使用法:

  • first[c][k]に変更first[c*m+k]
  • second[k][d]に変更second[k*p+d]
  • multiply[c][d]に変更first[c*m+d]

free:(forループなし)

  • free(first);
  • free(second);
  • free(multiply);
于 2013-02-17T18:11:26.827 に答える