【问题标题】:Accessing pointers in a pointer to a union访问指向联合的指针中的指针
【发布时间】:2016-04-25 02:56:17
【问题描述】:

所以我有一个包含联合的结构如下:

struct FILL{
  char *name;
  int id;
};

struct TEST{
  union{
    struct FILL *fill;
    int type;
  } *uni;
};

我不明白如何访问结构中的工会成员。我一直在尝试这样做:

struct TEST *test_struct, *test_int;

test_struct = malloc(sizeof(struct TEST));
test_struct->uni = malloc(sizeof(struct TEST));
test_struct->uni->fill->name = NULL;
test->struct->uni->fill->id = 5;

test_int = malloc(sizeof(int));
test_int->uni->type = 10;

但是当我尝试这个时我得到了段错误。我访问这些错误吗?不然怎么办?

编辑:对不起,我专注于格式,我搞砸了 TEST 的声明。已经修好了。

【问题讨论】:

  • 提供一份完整正确的struct TEST声明如何?您提交的内容似乎被截断了。
  • 不抱歉,这是我的错误,我已经更正了,但这是完整的声明。
  • type 在 union 内部的目的是什么,如果您永远无法使用它?您应该将type 放在结构中,其余的放在联合中。
  • 为什么我永远无法使用它?我的想法是我要么输入要么填写 TEST 结构。
  • 我建议您尝试编写一个不动态分配所有内容的版本。现在你正试图理解联合,同时也遇到了动态分配的问题。把这两件事分开弄清楚,然后再考虑把它们结合起来。正如 Fluter 的回答所指出的那样,您当前的问题实际上更多是在分配方面。

标签: c pointers struct unions


【解决方案1】:

结构的每个指针成员都必须初始化,要么通过malloc分配动态存储空间,要么分配给其他变量。以下是您的代码的问题:

struct TEST *test_struct, *test_int;

test_struct = malloc(sizeof(struct TEST));
test_struct->uni = malloc(sizeof(struct TEST)); // uni should be allocated with size of the union, not the struct
test_struct->uni->fill->name = NULL; // uni->fill is a pointer to struct FILL, it should be allocated too before accessing its members
test->struct->uni->fill->id = 5;

test_int = malloc(sizeof(int)); // test_int is of type struct TEST, you are allocating a integer here
test_int->uni->type = 10; // same, uni not allocated

所以尝试以下修复:

struct TEST *test_struct, *test_int;

test_struct = malloc(sizeof(struct TEST));
test_struct->uni = malloc(sizeof(*test_struct->uni));        
test_struct->uni->fill = malloc(sizeof(struct FILL));
test_struct->uni->fill->name = NULL;
test_struct->uni->fill->id = 5;

test_int = malloc(sizeof(struct TEST));
test_int->uni = malloc(sizeof(*test_struct->uni));

【讨论】:

  • 有什么问题?为什么下降?
  • 我不确定是谁做的?但这正是我所需要的,非常感谢!似乎我对工会有一个根本性的误解,我认为当我分配内存时,我会为我正在使用的工会的任何成员分配内存,而工会的大小就是那个成员的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 2012-06-07
  • 2017-01-04
  • 2011-08-04
  • 1970-01-01
相关资源
最近更新 更多