[英]C - Initializing structs inside a 2D array before returning double pointer from function
I'm new to C Programming and want to focus on learning dynamic allocation. 我是C编程的新手,想专注于学习动态分配。 As a learning opportunity for me, I'm trying to create a function that returns a double-pointer for a 2D array of structs. 作为我的学习机会,我正在尝试创建一个为二维结构数组返回双指针的函数。 I've been referencing tutorials that generally refer to what is mentioned here in approach #3 . 我一直在参考教程,这些教程通常指的是方法3此处提到的内容。
I can see that the tutorial assigns integer values no problem, but I'm not sure how that translates with structs. 我可以看到该教程为整数值赋值没有问题,但是我不确定该如何使用结构转换。
Here's my code so far: 到目前为止,这是我的代码:
#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;
}
This code segfaults, and I'm not too sure why. 此代码段错误,我不太清楚为什么。 Any help is appreciated. 任何帮助表示赞赏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.