Battleship program -- Structs and Arrays

My friend and I are working on a battleship program. We want to use a player struct and two variables (player one, player two) so that we can use the same functions and just pass one or two in depending on our needs.

We are getting a segmentation fault (core dump) at line 55 where it uses **which.board instead of **board. What's going wrong?

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <iostream>

using namespace std;

struct player{
	int row;
	int col;
	char **board[11][11];
};

int initialize_board1(player &which){

	char **board = new char*[11]; //initializes array for these values.
	for(int i = 0; i < 11; i++){
		board[i] = new char[11];
	}

	for(int i=1; i < 11; i++){ //sets all array spots = 0.
		for(int j = 1; j < 11; j++)
			**which.board[i][j] = '0';
		
	}

	for(int j = 1; j < 11; j++){
		**which.board[0][j] = 64 +  j;
	}

	for(int i = 1; i < 11; i++){
		**which.board[i][0] = 48 + i;
	}

	**which.board[1][1] = 'S';// Carrier.
	**which.board[1][2] = 'S';
	**which.board[1][3] = 'S';
	**which.board[1][4] = 'S';
	**which.board[1][5] = 'S';

int main(){

	player one;
	player two;

	int cont=1;

	intro();
	initialize_board1(one);
	system("clear");

	while(cont == 1){
		print_board_player(one);
		print_board_opponent(one);
		determine_player_choice(one);
		fill_board(one);
		system("clear"); //Skips to the next screen and continues printing.
		cont = check_for_winner(cont, one);
	}

	return 0;

}
Last edited on
You need to provide the function causing the error. And why use pointer to pointers?
Its because you never actually modify 'which's board variable. Try changing your initialize_board1 function to this:
1
2
3
4
    which.board = new char* [11];
    for (int i = 0; i < 11; ++i)
        which.board[i] = new char[11];
    ...


and your player class to this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class player { 
    int row;
    int col;
    char** board; // we don't want a two dimensional array of pointer pointers

    // initialize board to not point to anything
    player() : row(0), col(0), board(nullptr) {}

    // add a destructor to clean up when your program is done.
    ~player() {
        if (!board) return; // board was never allocated
        for (int i = 0; i < 11; ++i)
            delete[] board[i];
        delete[] board;
    }
};


EDIT:
@Cody0023: Pointer to Pointers = Pointer to arrays = arrays of arrays
Basically, @altenhos is using 2 Dimensional arrays.
Last edited on
Great, thanks! It does just what I need it to now :)
Topic archived. No new replies allowed.