我在做矩阵乘法,我需要做一个m x n数组和一个p x q数组。
但是,我不知道怎么做。
这是我的程序,当我手动输入值时,它会打印正确的输出:

#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。你不需要弗拉斯来完成这个任务。
至于实际的问题是:无法初始化可变长度数组。你必须一个一个地分配给他们的元素,或者使用一些质量分配技术,比如memcpy()

关于c - 如何在C中声明一个可变大小的数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18936855/

10-13 06:59