C-内存分配
1 malloc
1.1 malloc 不同平台的现象
| 平台 | 说明 |
|---|---|
| MSVC | 不会初始化内存值。 |
| LINUX | 会初始化内存值为0. |
int *players = malloc(sizeof(int) * PLAYER_COUNT);
1.2 初始化内存区域
需要配合初始化内存区域函数使用
void InitPointer(int **ptr, int length, int default_value) {
*ptr = malloc(sizeof(int) * length);
for (int i = 0; i < length; ++i) {
(*ptr)[i] = default_value;
}
}
int main (){
int *players;
players = calloc(PLAYER_COUNT, sizeof(int));
}
2 calloc
calloc 在所有平台上都会清零内存区域。
players = calloc(PLAYER_COUNT, sizeof(int));
3 realloc
realloc 是扩展内存C库函数。
players = realloc(players, PLAYER_COUNT * 2 * sizeof(int));
4 需要判断是否扩展成功。
if(players){
}else
{
}
free(players);