2016-04-23 77 views
-4

我想解決CodeChef問題。每當我運行它時,我都會遇到分段錯誤。這是鏈接的問題:Malvika is peculiar about color of balloons處理分段錯誤

這裏是我的代碼:

#include<iostream> 
#include<cstring> 
#include<algorithm> 

int main(){ 
    std::string balloonColors; 
    size_t numberOfAmber; 
    size_t numberOfBrass; 
    int t; 
    int results[t]; 

    std::cin >> t; 

    for (int i = 0; i < t; i++){ 
     int result = 0; 
     std::cin >> balloonColors; 
     numberOfAmber = std::count(balloonColors.begin(), balloonColors.end(), 'a'); 
     numberOfBrass = std::count(balloonColors.begin(), balloonColors.end(), 'b'); 

     if (numberOfAmber == 0 || numberOfBrass == 0){ 
      result = 0; 
     } 

     if (numberOfAmber <= numberOfBrass){ 
      result = (int)numberOfAmber; 
     } 
     else { 
      result = (int)numberOfBrass;  
     } 

     results[i] = result; 

    } 
    for (int x = 0; x < t; x++){ 
     std::cout << results[x] << std::endl; 
    } 
} 
+1

您使用調試器和單步一行程序行,直到段錯誤發生。然後檢查所有的變量值。 –

回答

0

這些線路的問題是:

int t; 
int results[t]; 

您使用未初始化變量聲明tresults。未初始化的變量具有未定義的值,並且在初始化之前使用它會導致未定義的行爲

您應該使用這裏std::vector,並設置其大小,一旦你從用戶那裏得到的實際尺寸:在C++需要

int t; 
std::vector<int> results; 

std::cin >> t; 

results.resize(t); 
+0

啊,我明白了。非常感謝你! –

0

陣列有一個固定的大小。您定義了results,其大小爲t,這是不固定的。

要使用動態的大小,使用std::vector代替:

#include <vector> 
... 
int t; 
std::cin >> t; 
std::vector<int> results (t);