fork download
  1. #include <stdio.h>
  2. #include <stdlib.h> // mallocとfreeを使うために必要です
  3.  
  4. int main() {
  5. int rows, cols;
  6.  
  7. // 1. 行数と列数の入力
  8. printf("行数を入力してください: ");
  9. if (scanf("%d", &rows) != 1) return 1;
  10.  
  11. printf("列数を入力してください: ");
  12. if (scanf("%d", &cols) != 1) return 1;
  13.  
  14. // 2. どんな環境でもエラーにならない「動的メモリ確保」による2次元配列の作成
  15. double **matrix = (double **)malloc(rows * sizeof(double *));
  16. if (matrix == NULL) {
  17. printf("メモリ確保に失敗しました。\n");
  18. return 1;
  19. }
  20. for (int i = 0; i < rows; i++) {
  21. matrix[i] = (double *)malloc(cols * sizeof(double));
  22. if (matrix[i] == NULL) {
  23. printf("メモリ確保に失敗しました。\n");
  24. return 1;
  25. }
  26. }
  27.  
  28. // 3. 各要素に数値を入力
  29. printf("\n%d行 %d列の行列の要素を入力してください:\n", rows, cols);
  30. for (int i = 0; i < rows; i++) {
  31. for (int j = 0; j < cols; j++) {
  32. printf("要素 [%d][%d]: ", i + 1, j + 1);
  33. if (scanf("%lf", &matrix[i][j]) != 1) return 1;
  34. }
  35. }
  36.  
  37. // 4. 入力された2次元配列を表示
  38. printf("\n--- 入力された2次元配列 ---\n");
  39. for (int i = 0; i < rows; i++) {
  40. for (int j = 0; j < cols; j++) {
  41. printf("%g\t", matrix[i][j]); // \tで列を綺麗に揃えます
  42. }
  43. printf("\n");
  44. }
  45.  
  46. // 5. 使い終わったメモリを綺麗に片付ける(解放)
  47. for (int i = 0; i < rows; i++) {
  48. free(matrix[i]);
  49. }
  50. free(matrix);
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 5316KB
stdin
5 5
10 -2 0 0 0
-2 9 -1 0 0
0 -1 8 -2 0
0 0 -2 7 -1
0 0 0 -1 5
stdout
行数を入力してください: 列数を入力してください: 
5行 5列の行列の要素を入力してください:
要素 [1][1]: 要素 [1][2]: 要素 [1][3]: 要素 [1][4]: 要素 [1][5]: 要素 [2][1]: 要素 [2][2]: 要素 [2][3]: 要素 [2][4]: 要素 [2][5]: 要素 [3][1]: 要素 [3][2]: 要素 [3][3]: 要素 [3][4]: 要素 [3][5]: 要素 [4][1]: 要素 [4][2]: 要素 [4][3]: 要素 [4][4]: 要素 [4][5]: 要素 [5][1]: 要素 [5][2]: 要素 [5][3]: 要素 [5][4]: 要素 [5][5]: 
--- 入力された2次元配列 ---
10	-2	0	0	0	
-2	9	-1	0	0	
0	-1	8	-2	0	
0	0	-2	7	-1	
0	0	0	-1	5