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

时间:2017-10-12 16:38:09

标签: c++

语言: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);
    }

}

1 个答案:

答案 0 :(得分:0)

您有阵列索引问题

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];
    }   
}

内循环完成一次后,迭代一次。

在内循环的两次完成之后,你已经迭代了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。还可以看到:What's the difference between a VLA and dynamic memory allocation via malloc?