我是一名刚学习 c++ 的新编程学生。我正在为一项任务处理扫雷克隆,但我遇到了分段错误。我不知道它发生在哪一行,因为我在 puTTy 中运行程序并在 emacs 中编写它。它们中的任何一个是否提供了一些功能来定位我不知道的分段错误?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int ROWS = 9;
const int COLS = 26;
void populate_board(int array[][COLS]);
void print_board(int array[][COLS]);
int main(){
int choice;
int targets[ROWS][COLS];
int guessed_spaces[ROWS][COLS];
populate_board(targets);
do{
cout << "Press '0' to exit." << endl;
cin >> choice;
switch(choice){
case 0:
break;
default:
print_board(targets);
}
}while (choice !=0);
}
void populate_board(int targets[][COLS]){
int row = 0;
int col = 0;
for(row = 0; row < ROWS; row++){
for(col = 0; col < COLS; row++){
srand (time(NULL));
int random = rand() % 2;
targets[row][col] = random;
}
}
}
void print_board(int targets[][COLS]){
int row = 0;
int col = 0;
for(row = 0; row < ROWS; row++){
cout << row << "|";
for(col = 0; col < COLS; col++){
cout << targets[row][col] << " ";
}
cout << "|" << endl;
}
cout << " - - - - - - - - - - - - - - - - - - - - - - - - - - -" << endl;
cout << " A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" << endl;
}
这里 :
for(row = 0; row < ROWS; row++)
{
for(col = 0; col < COLS; row++)
{
srand(time(NULL));
int random = rand() % 2;
targets[row][col] = random;
}
}
您在内循环和外循环中row
递增两次。因此,它将超越targets
界限。您需要将其更改为:
for(row = 0; row < ROWS; row++)
{
for(col = 0; col < COLS; col++)
{
srand(time(NULL));
int random = rand() % 2;
targets[row][col] = random;
}
}