我已經寫了一個過程,創建2個矩陣並將它們相乘。然而,我必須將我的代碼分成函數,並且我在聲明一個將爲矩陣分配內存的函數時遇到問題。C函數分配內存
這裏是我的代碼:
void matrixMult(){
int **A, **B, **C; //matrices
int rowA, colA, rowB, colB; //rows and columns
int i, j, k; //for iterations
printf("Number of rows in matrix A: \n");
scanf("%d", &rowA);
printf("Number of columns in matrix A: \n");
scanf("%d", &colA);
printf("Number of rows in matrix B: \n");
scanf("%d", &rowB);
printf("Number of columns in matrix B: \n");
scanf("%d", &colB);
//memory allocation
A = (int**)malloc(rowA * sizeof(int));
B = (int**)malloc(rowB * sizeof(int));
C = (int**)malloc(rowA * sizeof(int));
for (i = 0; i < rowA; i++)
{
A[i] = (int*)malloc(colA * sizeof(int));
}
for (i = 0; i < rowB; i++)
{
B[i] = (int*)malloc(colB * sizeof(int));
}
for (i = 0; i < rowA; i++)
{
C[i] = (int*)malloc(colB * sizeof(int));
}
/*
the rest of code
*/
}
應該這個函數是什麼樣的?
這有什麼錯呢?它不起作用嗎?它慢嗎?它會導致內存泄漏嗎?難看嗎? – Beta
http://stackoverflow.com/questions/35542391/segmentation-fault-but-unable-to-reason-how-memory-allocation-looks-fine-to-me –
http://stackoverflow.com/questions/605845/do-i-cast-result-of-malloc –