【发布时间】:2018-04-11 18:27:32
【问题描述】:
我有这样的结构:
typedef struct s_points
{
double x;
double y;
double z;
int color;
} t_points;
typedef struct s_map
{
int width;
int height;
t_points ***points;
} t_map;
我想在我的***points; 中读取和存储一个二维数组,但我不知道如何正确分配它。
这是我的代码(在 map->width 和 map->height 中,我存储输入数组的宽度和高度):
t_map *validate(int fd, char *av)
{
int lines;
int j;
char *tmp;
t_map *map;
t_points **tmp_p;
j = 0;
if (!(map = (t_map*)malloc(sizeof(t_map))))
error("ERROR: malloc error");
if ((!(map->points = (t_points***)malloc(sizeof(t_points**) * map->height)))
error("ERRROR!");
while((get_next_line(fd, &tmp)) > 0) //get_next_line will read input line by line
{
if (!(map->points[j] = (t_points**)malloc(map->width * sizeof(t_points*))))
error("ERROR: malloc error");
/* Some other code */;
j++;
}
return(map);
}
它有效,但是当我尝试在map->points[x][y]; 中写一些东西时,我有段错误,所以,据我所知,我在内存分配方面犯了错误。所以我无法理解如何以正确的方式做到这一点。
【问题讨论】:
-
***int不是二维数组,也不能指向一个。指针永远不是数组!成为三星级 (***) 程序员也不是恭维。它几乎总是表明接口/设计不好。说:阅读有关指针和数组以及动态内存分配的信息。每本 C 教科书都对它们进行了解释。
标签: c arrays memory-management struct