首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

怎么初始化含有结构体成员的结构体

2012-03-04 
如何初始化含有结构体成员的结构体?有两个结构体如下:structmyint{inta}structmyint2{structmyintb}并

如何初始化含有结构体成员的结构体?
有两个结构体如下:
struct   myint{
int   a;
};

struct   myint2{
struct   myint   b;
};

并有struct   myint   x   =   {1};
如果定义struct   myint2   y,并且我希望y.b为x,那么应该怎么初始化呢?使用形如
struct   myint   x   =   {...}的形式。谢谢

[解决办法]
#include <iostream>
using namespace std;

struct myint
{
int a;
int c;
};

struct myint2
{
struct myint b;
int d;
};


int main()
{
struct myint x = {1,2};
struct myint2 y = {x.a,x.c,10};

cout < <y.b.a < <endl;
cout < <y.b.c < <endl;
cout < <y.d < <endl;
return 0;
}
[解决办法]
#include <stdio.h>

struct st1 {
int a;
int b;
};
struct st2 {
struct st1 s;
int c;
};
int main(void)
{
struct st1 a={1,2};
struct st2 b={a,3};
printf( "%d%d%d%d%d ",a.a,a.b,b.s.a,b.s.b,b.c);
getchar();
}


dev c++ 编译运行通过

热点排行