2015-02-24 102 views
0
int main(){ 
    int size; 

    cout << "How many vertices? \n"; 
    cin >> size; 

    while (size > 20 || size < 0) { 
    cout << "Error. Enter new number: "; 
    cin >> size; 
    } 

    int graph[size][MAX_VERTICES],x,y; 
    InitializeGraph(graph, size); 
    while(x != 0 || y != 0) { 
    for(int i = 0; i<= size; i++){ 
    cout << "Enter a vertex pair(0 0 to end): "; 
    cin >> graph[x][y]; 
    } 
    } 
} 

当我在我的程序中运行此代码时,出现分段错误错误,我不知道我在做什么错误。有什么建议么?运行代码并得到分段错误错误

+0

什么'graph'?你如何声明和初始化它?如果它是一个数组或向量,那么在将它们用作索引之前,需要检查“x”和“y”是否在范围内。 – 2015-02-24 17:31:50

+0

请发布'graph'声明为什么,发生崩溃时'x'和'y'的值是什么。 – PaulMcKenzie 2015-02-24 17:32:27

+0

你永远不会改变x和y,所以如果它们不是0,那么你会得到一个无限循环。 – NathanOliver 2015-02-24 17:32:29

回答

0

当你声明本地(非静态)变量时,它们将不会被初始化,它们的值将是不确定的(实际上它们看起来是随机的)。使用这种变量除了初始化它将导致undefined behavior,这是崩溃最常见的原因之一。

你正在做什么是通过使用这些未初始化的变量作为数组的索引写入内存中的随机位置。


你似乎想要做的是首先读取x和y值,然后读取一个值到该位置。

我建议是这样的:

std::vector<std::vector<int>> graph(size, std::vector<int>(MAX_VERTICES)); 
unsigned int x, y; // No negative numbers allowed 

while (true) 
{ 
    std::cout << "Please enter two vertices (end with any being 0): "; 
    if (std::cin >> x >> y) 
    { 
     if (x > size || y > MAX_VERTICES) 
     { 
      std::cout << "Those vertices are to big, pleas try again\n"; 
      continue; 
     } 
     if (x == 0 || y == 0) 
      break; // End of input 

     std::cout << "Please enter a value for (" << x << ',' << y << '): "; 
     // -1 because the indexes entered by the user are 1-based, 
     // vector indexes are 0-based 
     std::cin >> graph[x - 1][y - 1]; 
    } 
    else 
    { 
     if (std::cin.eof()) 
      break; // User terminated input by end-of-file 
     else 
     { 
      std::cout << "Please enter two integer values equal or larger than zero.\n"; 
      std::cin.clear(); // Clear the error, and try again 
     } 
    } 
} 
相关问题