[英]malloc of matrix of struct - C
我正在做一個游戲項目。 我的一個結構包含另一個結構的矩陣。 我無法管理malloc。 這是我的實際代碼:
m->tiles = malloc(sizeof(struct *tile)*width);
for (i=0; i<width ; i++){
m->tiles[i] = malloc(sizeof(struct tile)*height);
}
我得到了這個錯誤信息:
map.c:111:37: error: expected ‘{’ before ‘*’ token
m->tiles = malloc(sizeof(struct *tile)*width);
我以前沒做過 已經為int矩陣分配了內存,但從未為struct矩陣分配內存。
謝謝。
編輯:謝謝BLUEPIXY,您的回答有效。 但是我認為我沒有很好地定義我的結構:
struct map{
int map_width; // Nombre de tiles en largeur
int map_height; // Nombre de tiles en hauteur
struct tile **tiles; // ensemble des tiles de la map
};
應該是“ struct tile *** tiles”嗎?
struct map{
int map_width;
int map_height;
struct tile **tiles;
};
...
m->tiles = malloc(sizeof(struct tile*)*height);
for (i=0; i<height ; i++){
m->tiles[i] = malloc(sizeof(struct tile)*width);
}
解釋性說明
Type **var_name = malloc(size*sizeof(Type *));
要么
Type **var_name = malloc(size*sizeof(*var_name));
使用struct tile **tiles
就足夠了。 這樣想:
struct tile_array *tiles
顯然足以指向tile_array
指針數組。 現在,為了避免其他struct
,請使用指向圖塊的指針替換tile_array
。 結果,您有一個指向tile
類型的指針的指針。 指向tile
的指針表示tile
數組的開始。 指向tile
指針的指針表示此類指針數組的開始。
這個
m->tiles = malloc(sizeof(struct *tile)*width);
應該
m->tiles = malloc(width * sizeof(struct tile *));
因此,固定代碼應如下所示
m->tiles = malloc(width * sizeof(struct tile *));
if (m->tiles == NULL)
cannotAllocateMemoryAbortPlease();
for (i = 0 ; i < width ; ++i)
m->tiles[i] = malloc(height * sizeof(struct tile));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.