C structure initialization? [duplicate]

感情迁移 提交于 2019-12-30 05:57:40

问题


How can I initialize a structure if one field in the structure is itself a structure?


回答1:


You need to use more braces (actually, they're optional, but GCC makes a warning these days). Here's an example:

struct s1 { int a; int b; };
struct s2 { int c; struct s1 s; };

struct s2 my_s2 = { 5, { 6, 3 } };



回答2:


Nesting of structure

You can initialize a structure if one field in the structure is itself a structure

struct add{
    int house;
    char road;
};
struct emp{
    int phone;
    struct add a;
};

struct emp e = { 123456, 23, "abc"};
printf("%d %d %c",e.phone,e.a.house,e.a.road);



回答3:


struct A
{
int n;
}

struct B
{
A a;
} b;

You can initialize n by the following statement. Is this what you are looking for.

b.a.n = 10;


来源:https://stackoverflow.com/questions/3177372/c-structure-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!