語言:C++ 系統:Linux: 編譯:G ++ prog.cpp -o PROG爲什麼「std :: cin >> secondMatrix [i * twoColoumn + j];」給我段錯誤
這是問題所在。我有一個程序,讓用戶插入兩個矩陣的大小(我保持矩陣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);
}
}
VLA的不是一個真正的C++的東西。雖然由一些編譯器支持。 – Ron
我想是時候瞭解你的調試器是如何工作的,所以你可以檢查所有變量的值。 – nvoigt
@Ron即使它們受編譯器擴展支持,堆棧大小仍然有限。 – user0042