繁体   English   中英

C-在从函数返回双指针之前,在2D数组中初始化结构

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM