Calling 2D vector elements is causing a crash?

Hi! Right now I'm trying to just have the grid() function print out the initialized tic tac toe board. It all compiles successfully but, for some reason I can't figure out just yet, the grid() prints out the first line and then it all crashes. So, I think something has to be wrong about using box[#][#]. I'm really stumped.


Here is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* Lab 10: Tic-Tac-Toe Game */

#include <iostream>
#include <vector>

using namespace std;


// Function prototypes:

void grid();
vector< vector<char> > box;


// Main:

int main(int argc, char** argv){

	// Initializing board:
	vector< vector<char> > box(3, vector<char> (3, ' '));

	grid();


	return 0;
}

// The tic-tac-toe grid:

void grid(){
	cout << "     |     |     \n";
	cout << "  "<< box[0][0] <<"   |  "<< box[0][1] << "   |  " << box[0][2] <<'\n';
	cout << "_____|_____|_____\n";
	cout << "     |     |     \n";
	cout << "  "<< box[1][0] <<"   |  "<< box[1][1] << "   |  " << box[1][2] <<'\n';
	cout << "_____|_____|_____\n";
	cout << "     |     |     \n";
	cout << "  "<< box[2][0] <<"   |  "<< box[2][1] << "   |  " << box[2][2] <<'\n';
	cout << "     |     |     \n";
}
Because the box in main is not the same box that you have declared globally.

Consider getting rid of that global variable and passing it as a parameter to the grid function instead:
1
2
3
4
5
6
7
8
9
10
void grid(const vector<vector<char>>& box);

int main()
{
    vector<vector<char>> box(3, vector<char>(3, ' '));
    grid(box);
}

void grid(const vector<vector<char>>& box){
    // ... 
Oh, wow. I feel silly.

I should probably practice with scopes of functions/variables.

Thanks!
Topic archived. No new replies allowed.