2017-10-12 41 views
-3

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

} 
+0

VLA的不是一個真正的C++的東西。雖然由一些編譯器支持。 – Ron

+0

我想是時候瞭解你的調試器是如何工作的,所以你可以檢查所有變量的值。 – nvoigt

+0

@Ron即使它們受編譯器擴展支持,堆棧大小仍然有限。 – user0042

回答

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

內環的一個完成之後,你迭代oneRow倍。

經過兩次內循環完成後,您已經迭代了2 * oneRow次。

... 等

你想:

firstMatrix[i*oneRow + j] 

此外,正如其他人所指出的,下面兩行的堆棧VLAS上聲明您陣列(可變長度數組),因爲值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?

相關問題