使用结构的嵌套结构初始化

时间:2017-06-26 09:36:29

标签: c struct

也许这是重复但我无法找到适合这个问题的解决方案...而且我有点像C开发的新手,我的问题是我不知道如何初始化嵌套struct,请查看更多信息...... 事情如下:

// another_struct.h
struct AnotherStruct {
    void (*some_function)();
}
extern struct AnotherStruct AnotherStruct;

// yet_another_struct.h
struct YetAnotherStruct {
    void (*some_function)();
}
extern struct YetAnotherStruct YetAnotherStruct;

// my_struct.h
struct MyStruct1 {
    struct AnotherStruct another;
    struct YetAnotherStruct and_yet;
}
extern struct MyStruct1 MyStruct1;

在各自的.C文件中:

struct AnotherStruct AnotherStruct = {
    .some_function = blabla
};

struct YetAnotherStruct YetAnotherStruct = {
    .some_function = blablabla
};

// I want the initialization of MyStruct1 to have the struct pointing to the structs
struct MyStruct1 MyStruct1 = { /* ?? */ };

/* I was thinking something like this */
struct MyStruct1 MyStruct1 = {
    .another = AnotherStruct,
    .and_yet = YetAnotherStruct
};

但编译器抱怨xD 因此,我的最终目标是能够以下列方式访问子结构:

MyStruct1.another.some_function();

非常感谢,如果这个问题重复或者是通往菜鸟的话,我很抱歉:)

2 个答案:

答案 0 :(得分:1)

为什么不像这样构造它们(没有指针使用):

/* I was thinking something like this */
struct MyStruct1 MyStruct1 = {
    .another = { //.another is your struct, just do construct like normal
        .some_function = blabla
    },
    .and_yet = { //The same here.
        .some_function = blablabla
    }
};

代码中的用法是:

//Call function
MyStruct1.another.some_function();

使用指针:

// my_struct.h, add pointers
struct MyStruct1 {
    struct AnotherStruct *another; //Added pointers
    struct YetAnotherStruct *and_yet; //Here too
}

然后在.c

中使用
struct AnotherStruct AnotherStruct = {
    .some_function = blabla
};
struct YetAnotherStruct YetAnotherStruct = {
    .some_function = blablabla
};

/* I was thinking something like this */
struct MyStruct1 MyStruct1 = {
    .another = &AnotherStruct, //Added & for address
    .and_yet = &YetAnotherStruct //Added & for address
};

稍后访问您的值,例如:

//Call your function now
MyStruct1.another->some_function();

答案 1 :(得分:-1)

@ tilz0R没有足够的回复评论。对你的回答稍加修改。

Now we move them here to make the compiler find them automatically

至于union thingie,可能是关于Microsoft扩展语法

<?
$result = 1;
?>
some html code...
<?php
$result2 = $result;
?>

不幸的是,这是一个非标准的扩展,而且它注定永远不会成为一个,因为这是委员会决定保持与C ++的兼容性。

Per @Lundin评论。现代C中确实可以使用以下代码:

typedef struct {
  int a_val;
} A;

typedef struct {
  float b_val;
} B;

typedef struct {
  A *a;
  B *b;
} C;

C c = {
  .a = &(A){ .a_val = 1 },
  .b = &(B){ .b_val = 1. },
};

然而,如果将结构嵌入到结构中,这几乎没有任何好处(除了组织代码)。虽然它比联盟更酷:

typedef struct {
  A;
  B;
} C;

C c;

c.a_val = 1; // valid

使用的编译行:

typedef struct {
  struct {
    int a_val;
  };
  struct {
    float b_val;
  };
} C;

C c;

c.a_val = 1;