读书人

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

发布时间: 2012-03-04 11:13:33 作者: rapoo

如何初始化含有结构体成员的结构体?
有两个结构体如下:
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++ 编译运行通过

读书人网 >C语言

热点推荐