已编辑:从类型“struct Bar *”分配给类型“struct Bar”时类型不兼容

Edited: incompatible types when assigning to type ‘struct Bar’ from type ‘struct Bar *’

编辑:清理了代码以避免在问题上造成混淆。至于问题:我想分配大小为 struct Foo2 的内存。然后分配大小为 struct Bar 的内存并将该位置分配给 a->b。之后我想将 a->b.x 设置为一个整数值。生成此代码是为了了解为结构分配内存并设置其值的概念。

如何访问 a->b?我知道我不能设置指向它的指针。

Error:  incompatible types when assigning to type ‘struct Bar’ from
type ‘struct Bar *’?

另外,为什么我不能在没有 error: unknown type name ‘Bar’ 的情况下将 typedef struct Bar 放在 Foo2 的结构之后?

typedef struct ForwardClassTest ForwardClassTest;
typedef struct Foo2 Foo2;
typedef struct Bar Bar;
struct ForwardClassTest {
};
struct Bar {
    int x;
};
struct Foo2 {
    Bar b;
};
int main();
  //Foo2 a
  Foo2 * a = (Foo2 *) malloc(sizeof(Foo2));
  //a=new Foo2()
  a = (Foo2*) malloc(sizeof(Foo2));
  //a.b=new Bar()
  a->b = (Bar*) malloc(sizeof(Bar));
  //a.b.x=5
  a->b.x = 5;
  exit(0);
}
  1. 这一行 Foo2 *a = (Foo2 *) malloc(sizeof(Foo2)) 应该是 Foo2 * a = malloc(sizeof(Foo2))
  2. a->b = (Bar*) malloc(sizeof(Bar)); 不是必需的,因为 b 不是指针
  3. 东西:

    typedef struct ForwardClassTest ForwardClassTest; typedef struct Foo2 Foo2; typedef struct Bar Bar; typedef struct ForwardClassTest {

不需要

  1. 这是错误的 void* main(char* args[]){ 应该是 int main(int, char**) 因为没有使用参数。
  2. 使用free释放内存

因为没有完整的答案@ed-heal 给我指出了正确的方向。我制定了解决方案。唯一的方法是在 Foo2 中添加指向 Bar b 的指针。

typedef struct Foo2 Foo2;
typedef struct Bar Bar;
struct Bar {
    int x;
};
struct Foo2 {
    Bar *b;
};
int main(){
  Foo2 * a = (Foo2 *) malloc(sizeof(Foo2));
  a = (Foo2*) malloc(sizeof(Foo2));
  a->b = (Bar*) malloc(sizeof(Bar));
  a->b->x = 5;
  free(a);
  free(a->b);
  exit(0);
}