为什么"std::cin >> secondMatrix[i*twoColoumn + j];"给我分段错误

Why "std::cin >> secondMatrix[i*twoColoumn + j];" give me segmentation fault

本文关键字:gt 错误 分段 cin std secondMatrix 为什么 twoColoumn      更新时间:2023-10-16

语言:c++系统:Linux:编译:g++ prog.cpp -o prog

这就是问题所在。我有一个程序,让用户插入两个矩阵的大小(我保持矩阵 1D 而不是 2D 作为练习)。给我带来问题的代码部分通常很好,除非我输入:

2
1
1
1

当我这样做时,输出是printf("4")和printf("5")之间的分割错误。

#include <iostream>
int main(void)
{
int oneColoumn, oneRow, twoColoumn, twoRow;
std::cout << "nHow many coloumns do you want for the first matrix?" << std::endl;
std::cin >> oneColoumn;
std::cout << "nHow many rows do you want for the first matrix?" << std::endl;
std::cin >> oneRow;
std::cout << "nHow many coloumns do you want for the second matrix?" << std::endl;
std::cin >> twoColoumn;
std::cout << "nHow many rows do you want for the second matrix?" << std::endl;
std::cin >> twoRow;
int firstMatrix[oneColoumn*oneRow];
int secondMatrix[twoColoumn*twoRow];
for(int i=0; i < oneColoumn; i++)
{
    for(int j=0; j < oneRow; j++)
    {
        std::cout << "Insert a number for the first matrix";
        std::cin >> firstMatrix[i*oneColoumn + j];
    }   
}
printf("1");
for(int i=0; i < twoColoumn; i++)
{printf("2");
    for(int j=0; j < twoRow; j++)
    {printf("3");
        std::cout << "Insert a number for the second matrix";
        printf("4");
        std::cin >> secondMatrix[i*twoColoumn + j];
        printf("5");
    }   
}
int threeColoumn, threeRow;
if(oneColoumn>twoColoumn)
    threeColoumn=twoColoumn;
if(oneRow>twoRow)
    threeRow=twoRow;
int thirdMatrix[threeColoumn*threeRow];
char choice;
std::cout<<"Do you want to add or multiply the two matrices?(a/m)"<<std::endl;
std::cin>>choice;
if(choice=='a')
{
    std::cout<<"The two matrices have been added"<<std::endl;
    //Addition(firstMatrix,oneRow,oneColoumn,secondMatrix,twoRow,twoColoumn,thirdMatrix,threeRow,threeColoumn);
}
else if(choice=='m')
{
    std::cout<<"The two matrices have been multiplied"<<std::endl;
    //Multiplication(firstMatrix,oneRow,oneColoumn,secondMatrix,twoRow,twoColoumn,thirdMatrix,threeRow,threeColoumn);
    }
}

您有一个数组索引问题

for(int i=0; i < oneColoumn; i++)
{
    for(int j=0; j < oneRow; j++)
    {
        std::cout << "Insert a number for the first matrix";
        std::cin >> firstMatrix[i*oneColoumn + j];
    }   
}

完成一次内部循环后,将迭代 oneRow 时间。

完成两次内部循环后,您已经迭代了 2*oneRow 时间。

。等

你想要:

    firstMatrix[i*oneRow + j]

此外,正如其他人指出的那样,以下两行将堆栈上的数组声明为 VLA(可变长度数组),因为oneColumnoneRow的值由用户提供,直到运行时才知道。

int firstMatrix[oneColoumn*oneRow];
int secondMatrix[twoColoumn*twoRow];

不一定受支持,但可能取决于您的编译器。 有关 gcc,请参阅 https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html。 还可以看到这个:VLA 和通过 malloc 进行动态内存分配有什么区别?