运行代码并获取分段错误错误

时间:2015-02-24 17:29:39

标签: c++

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

当我在程序中运行此代码时,出现分段错误错误,我不确定我做错了什么。有什么建议?

1 个答案:

答案 0 :(得分: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
        }
    }
}