저는 C를 처음 접했고 다음 구조에 malloc을 사용하는 적절한 방법을 알고 싶습니다.
struct cell {
struct player* owner;
int letter;
};
struct board {
struct cell** matrix;
int width;
int height;
};
이 구조는 malloc을 사용하여 생성 된 '보드'구조 안에 있습니다. 충분한 정보가 되었기를 바라며 설명해 주셔서 감사합니다.
struct cell {
struct player* owner;
int letter;
};
struct board {
struct cell** matrix;
int width;
int height;
};
//this would work, but memory allocation is slow.
void fillBoard(board *b){
b->matrix = (struct cell**)malloc(b->width * sizeof(struct cell*));
for (int i = 0; i < b->height; i++){
b->matrix[i] = (struct cell*)malloc(sizeof(struct cell));
}
}
//to limit that you could rewrite it to this.
struct cell {
struct player* owner;
int letter;
};
struct board {
struct cell* matrix;
int width;
int height;
};
//this only allocates memory once, so it is faster and it avoids memory fragmentation.
void fillBoard(board *b){
b->matrix = (struct cell*)malloc(b->width * b->height * sizeof(struct cell));
}
//to access a certain cell, you have to do this (x * width + y)
struct cell *getCell(board *b, int x, int y){
return &b->matrix[x * b->width + y];
}
편집 : 저는 보통 C로 프로그래밍하지 않습니다. 저는 주로 C ++를 사용하므로 약간의 실수가있을 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다