### 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?

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364`` ``````#include #include #include #include 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:
 ``1234`` `````` which.board = new char* [11]; for (int i = 0; i < 11; ++i) which.board[i] = new char[11]; ...``````

and your player class to this:
 ``12345678910111213141516`` ``````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.