那麼,我正在做矩陣乘法,我需要做一個m x n
陣列和p x q
陣列。
但是,我不知道如何去做。如何在C中聲明一個可變大小的數組?
這是我的節目,當我在值手動送入它打印正確的輸出:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
/*
Rows and columns for matrices.
*/
int m , n; // rows and columns of the first matrix
int p , q; // rows and columns of the second matrix
/*
1st matrix is a 2x3 matrix
*/
m = 2;
n = 3;
/*
2nd matrix is a 3x2 matrix
*/
p = 3;
q = 2;
/*
Create the matrices.
Give them values.
*/
int matrix1[m][n] = {
{2,3,4},
{5,6,7}
};
int matrix2[p][q] = {
{1,7},
{3,9},
{5,11}
};
/*
Check if we can multiple the matrices.
For matrix multiplication,
the number of COLUMNS of FIRST matrix must be equal to
the number of ROWS of SECOND matrix
*/
if(n==p){
/*
Create a new matrix.
The resulting matrix will have M rows and Q columns.
That is, the matrix is a MxQ matrix.
*/
int matrix3[2][2];
/*
We need three loops so we have 3 variables.
*/
int i = 0; // iterates over matrix1 rows
int j = 0; // iterates over matrix1 columns
int k = 0; // iterates over matrix2 rows
int l = 0; // iterates over matrix2 columns
while(i < m){
l = 0;
while(l < q){
int element = 0;
while(j < n && k < p){
element += matrix1[i][j] * matrix2[k][l];
matrix3[i][l] = element;
j++;
k++;
}
printf("\t%d",element);
l++;
j = 0;
k = 0;
}
printf("\n");
i++;
}
}else{
printf("Matrices can not be multiplied");
}
}
矩陣聲明被標記爲錯誤。 我該如何解決?
您的編譯器*支持* VLA嗎?並檢查你的錯誤。即使支持,VLA也不支持初始化程序。 – WhozCraig
@WhozCraig什麼? : -/VLA =可變長度數組。我使用Dev-C++,它使用GCC V 4.71 –
這個代碼中甚至沒有*需要*用於VLA。矩陣可以是常量大小的。 – WhozCraig