【问题标题】:How should I allocate my structure(pointer to array of structure)? [closed]我应该如何分配我的结构(指向结构数组的指针)? [关闭]
【发布时间】: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


【解决方案1】:

points 中的间接级别太多了。指针数组需要一层,t_points 数组需要一层:

typedef struct s_map
{
    int         width;
    int         height;
    t_points    **points;
}               t_map;

然后分配如下:

if ((!(map->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] = malloc(map->width * sizeof(t_points))))
        error("ERROR: malloc error");
    /* Some other code */;
    j++;
}

另外,don't cast the return value of malloc

【讨论】:

  • 正确答案(赞成)请考虑改用一维数组并将数据存储在row-major or column-major order 中。由于缓存局部性,这通常比二维数组更有效,并且可以说甚至产生更简单的代码,因为您不需要分配多级指针。即t_points *array1d = malloc(width * height * sizeof(t_points))
  • @TypeIA:这与在这里使用锯齿状数组一样大错特错。正确的方法是使用二维数组并将索引处理留给编译器。它的性能并不比手动计算地址差一点,但更不容易出错且更清晰。它还可以让编译器更好地优化,因为启发式方法主要用于简单且符合概念的模式。
  • @Olaf 我很不同意;请参阅this question 进行全面(呃)治疗。绝大多数图像处理代码专门使用一维数组是有原因的。
  • @TypeIA:简单的原因是大多数库都比引入 VLA 的 C99 更早。此外,人们坚持 1990 年代的 C noit 接受 C 的进步并试图说服用户使用垃圾代码。哦,当然它是 FORTRAN 兼容性的“圣杯”。即使没有打算使用这种语言。初学者应该首先学习如何编写可读和可维护代码,而不是无需兼容 1960ies 语言。关于。 “绝大多数”:大多数人类和苍蝇吃粪便。然而我不会推荐它。 (并不意味着它是大多数)
  • @Olaf FORTRAN 兼容性?屎?!我会让我的论点保持原样并同意(强烈)不同意这里......!
猜你喜欢
  • 2018-04-08
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 2017-09-01
  • 1970-01-01
相关资源
最近更新 更多