簡體   English   中英

在 c++ 中輸入可變大小的矩陣

[英]taking input in a matrix of variable size in c++

我正在嘗試檢查 c++ 中矩陣 A 的正交性。為此,我聲明了行數和列數的“MAX”值,然后我試圖獲取矩陣的行數和列數,因此聲明了它. 之后,我試圖通過使用指向矩陣行的指針等來獲取矩陣元素的輸入。

#include <stdio.h>
#define MAX 10
int arows,acolumns; /*line 4*/
void input_matix(float (*arr)[MAX],int arows,int acolumns)
{/*asks user for input of individual elements*/}

void transpose(float (*T)[MAX],float (*A)[MAX],int arows,int acolumns)
{/*gets me the transpose*/}
void product(float (*A)[MAX],float (*T)[MAX],float (*P)[MAX])
{/*multiplies two matrices and places the product in P matrix*/}

int orthogonal_array(float (*arr)[MAX]){/*returns 1 if arr is ortho*/}
int main()
{
    //int arows,acolumns;
    printf("Enter the no. of rows and columns of matrix A: \n");
    scanf("%d %d",&arows,&acolumns);
    float A[arows][acolumns];

    if (arows != acolumns)
    {
        printf("Not a orthogonal matrix.\n");
    }
    else
    {
        input_matix(A,arows,acolumns);
        orthogonal_array(A);
    }
}

編譯時出現錯誤

cannot convert 'float (*)[acolumns] to float (*)[10]' 

我試過將第 4 行替換為

extern int arows,acolumns;

並將 float (*arr)[MAX] 替換為float arr[][acolumns]與函數中的其他參數類似,但隨后出現錯誤

"expression must have a constant value"
"array bound is not a integer constant before "]" token */

請建議我應該怎么做,才能使這些功能正常工作

根本原因是在 C++ 中不允許使用 VLA(Varibale Length Arrays)。 到目前為止,它不是語言 C++ 的一部分。

float A[arows][acolumns];

C++ 代碼無效。

C可以,C++不行

在 C 中,您不能在程序中創建雙索引數組或更改其大小。 所以是的,你必須在編譯之前告訴程序 A 的大小是多少。

您可以使用其最大大小創建此數組,並在您的函數中發送“arows”和“acolumns”以僅在“已用空間”上工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM