![](/img/trans.png)
[英]Function requires a double pointer and uses a representation of 2D array inside
[英]C - Initializing structs inside a 2D array before returning double pointer from function
我是C編程的新手,想專注於學習動態分配。 作為我的學習機會,我正在嘗試創建一個為二維結構數組返回雙指針的函數。 我一直在參考教程,這些教程通常指的是方法3此處提到的內容。
我可以看到該教程為整數值賦值沒有問題,但是我不確定該如何使用結構轉換。
到目前為止,這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
const int HEIGHT = 64;
const int WIDTH = 96;
struct Tile
{
char type;
bool armed;
struct Tile* up;
struct Tile* right;
struct Tile* down;
struct Tile* left;
};
struct Tile** createTileMap(unsigned int w, unsigned int h)
{
struct Tile** map = (struct Tile **)malloc(w * sizeof(struct Tile *));
for (int x = 0; x < w; x++)
{
map[x] = (struct Tile *)malloc(h * sizeof(struct Tile));
for (int y = 0; y < h; y++)
{
map[x][y] = (struct Tile){.type = '_', .armed = false, .up = NULL,
.right = NULL, .down = NULL, .left = NULL};
}
}
}
int main(int argc, char* argv[])
{
struct Tile** map = createTileMap(WIDTH, HEIGHT);
for (int x = 0; x < WIDTH; x++)
{
for (int y = 0; y < HEIGHT; y++)
{
printf(" (%d, %d): ", x, y);
printf("%c", map[x][y].type);
}
printf("\n");
}
return 0;
}
此代碼段錯誤,我不太清楚為什么。 任何幫助表示贊賞。
如EOF所示 ,我只是忘了實際返回地址 。 幸運的是,我的其他代碼很好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.