#include void subtraction(double **matOut, double **matA, int matARows, int matACols, double **matB, int matBRows, int matBCols); int main(){ double **matOut, **matA, **matB; int matOutRows, matOutCols; int matARows, matACols, matBRows, matBCols; int i, j; matARows = 3; matACols = 3; matBRows = 3; matBCols = 3; // メモリ確保 matOut = malloc(sizeof(double*) * matARows); matA = malloc(sizeof(double*) * matARows); matB = malloc(sizeof(double*) * matBRows); for(i = 0; i < matARows; ++i){ matOut[i] = malloc(sizeof(double) * matACols); matA[i] = malloc(sizeof(double) * matACols); matB[i] = malloc(sizeof(double) * matBCols); } // データ初期化 for(i = 0; i < matARows; ++i){ for(j = 0; j < matACols; ++j){ matOut[i][j] = 0.0; matA[i][j] = i * matACols + j; matB[i][j] = i; } } // 初期状態確認 printf("matrixA initialized\n"); for(i = 0; i < matARows; ++i){ for(j = 0; j < matACols; ++j){ printf("%.3f ", matA[i][j]); } printf("\n"); } printf("matrixB initialized\n"); for(i = 0; i < matBRows; ++i){ for(j = 0; j < matBCols; ++j){ printf("%.3f ", matB[i][j]); } printf("\n"); } // 計算 subtraction(matOut, matA, matARows, matACols, matB, matBRows, matBCols); // 計算結果 printf("matrixOut\n"); for(i = 0; i < matARows; ++i){ for(j = 0; j < matACols; ++j){ printf("%.3f ", matOut[i][j]); } printf("\n"); } // メモリ解放 for(i = 0; i < matARows; ++i){ free(matOut[i]); free(matA[i]); free(matB[i]); } free(matOut); free(matA); free(matB); return 0; } /* matOut : 計算結果 matA : 入力行列A matARows : 入力行列Aの行数 matACols : 入力行列Aの列数 matB : 入力行列B matBRows : 入力行列Bの行数 matBCols : 入力行列Bの列数 */ void subtraction(double **matOut, double **matA, int matARows, int matACols, double **matB, int matBRows, int matBCols){ int i, j; if( (matARows != matBRows) || (matACols != matBCols) ){ printf("計算できません\n"); return; } for(i = 0; i < matARows; ++i){ for(j = 0; j < matACols; ++j){ matOut[i][j] = matA[i][j] - matB[i][j]; } } }