假设您要为use super::board::Board;
use super::player::Player;
use super::planatation::ResourceType;
#[derive(Debug)]
pub struct Game<'a> {
board: Board,
players: &'a [Player],
governor: &'a Player
}
impl<'a> Game<'a> {
pub fn new(names: &[String], players: &'a mut Vec<Player>) -> Self {
let num_of_players = names.len() as i32;
let board = Board::new(num_of_players);
if num_of_players < 3 || num_of_players > 5 {
panic!("Only 3, 4 or 5 players may play");
}
if num_of_players < 5 {
for (i, name) in names.iter().enumerate() {
if i < 2 {
players.push(Player::new(name.to_string(), ResourceType::Indigo));
} else {
players.push(Player::new(name.to_string(), ResourceType::Corn));
}
}
} else { // num_of_player == 5
for (i, name) in names.iter().enumerate() {
if i < 3 {
players.push(Player::new(name.to_string(), ResourceType::Indigo));
} else {
players.push(Player::new(name.to_string(), ResourceType::Corn));
}
}
}
Game {
board: board,
players: players,
governor: &players[0]
}
}
}
整数分配空间,以便可以使用带有一些索引和类似内容的循环在其中存储一些数据:
n
为什么您可以只做int main() {
int i, n, *mem;
n = 5;
if(mem = malloc(n*sizeof(int))) {
for(i = 0; i < n; i++) {
scanf("%d", (mem+i));
}
//do stuff with that data etc etc
free(mem); //the crucial part
return 0;
} else {
throw_some_error_and_exit();
}
}
而不是一个周期地做free(mem);
?程序如何在不给您分配给free(mem+i);
的{{1}}值的情况下跟踪分配(并释放)的内存量?