我正在尝试根据主线参数中声明的列和行数分配内存。例如a.out 2 4 6意味着要用2名玩家,4列,6行进行a.out比赛。
我期望通过board_init函数分配内存,但是valgrind返回:user_input_players(int,char **)]上的读取大小无效1
我只熟悉new和delete命令。我不确定如何理解错误消息。
// function declaration
int user_input_players(int choices, char** selection);
int user_input_columns(int choices, char** selection);
int user_input_rows(int choices, char** selection);
int board_init(int columns, int rows);
int main(int argc, char** argv) {
int column = 0, row = 0, player = 0;
player = user_input_players(argc, argv);
column = user_input_columns(argc, argv);
row = user_input_rows(argc, argv);
board_init(column, row);
return 0;
}
int user_input_players(int choices, char** selection){
int player_count = 0;
for(int i = 0; i < choices; i++){
selection[i];
}
while( !(*selection[1] == '1' || *selection[1] == '2')){
cout << "Please enter number of players: " << endl;
cin.clear();
cin >> player_count;
if(player_count == 1 || player_count == 2){
return player_count;
}
player_count = *selection[1];
return player_count;
}
}
int user_input_columns(int choices, char** selection){
int column_count = 0;
for(int i = 0; i < choices; i++){
selection[i];
}
column_count = atoi(selection[2]);
if(column_count >= 4 && column_count <= 20){
return column_count;
}
while( !(column_count >= 4 && column_count <= 20)){
cout << "Please enter number of columns: " << endl;
cin.clear();
cin >> column_count;
if(column_count >= 4 && column_count <= 20){
return column_count;
}
}
}
int user_input_rows(int choices, char** selection){
int row_count = 0;
for(int i = 0; i < choices; i++){
selection[i];
}
row_count = atoi(selection[3]);
if(row_count >= 4 && row_count <= 20){
return row_count;
}
while( !(row_count >= 4 && row_count <= 20)){
cout << "Please enter number of rows: " << endl;
cin.clear();
cin >> row_count;
if(row_count >= 4 && row_count <= 20){
return row_count;
}
}
}
int board_init(int columns, int rows){ // Valgrind shows no memory allocation because of error
int** board = new int*[rows];
for(int i = 0; i < rows; i++){
board[i] = new int[columns];
}
}
我正在尝试根据主线参数中声明的列和行数分配内存。例如a.out 2 4 6意味着要用2名玩家,4列,6行进行a.out比赛。我是...
如果允许使用矢量,请将init_board函数改为使用2d矢量: