2016-04-23 75 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);