2010-11-25 45 views
0

我想表明,前两个市民正在使用指针结婚一起在2009年(假设citiens是安东尼·霍普金斯和朱迪·福斯特)谢灵运在C.(指针使用情况,并显示关系)

struct citizen 
{ 
char sSSC[12]; 
char sFamilyName[16]; 
char sNames[24]; 
char cGender; //men ='m', women='w' 
citizen*pSpouse; //Null if not married 
int iYearOfMarriage; 

} 
citizen People[100000]; 
+0

你想要一个关于前两个条目(People [0]和People [1])的布尔型答案,还是你想要找到前两个已结婚的公民条目? – terminus 2010-11-25 17:08:32

+1

有什么问题?你是否收到编译器错误? – 2010-11-25 17:09:26

+1

你是否允许同性婚姻? – pmg 2010-11-25 17:09:32

回答

1

你的意思是,只是:

People[ANTHONY_HOPKINS].pSpouse = &People[JODIE_FOSTER]; 
People[JODIE_FOSTER].pSpouse = &People[ANTHONY_HOPKINS]; 
People[ANTHONY_HOPKINS].iYearOfMarriage = 
People[JODIE_FOSTER].iYearOfMarriage = 2009; 

或者我误解了这个问题? ''用于引用结构中的成员(或 - 如果有指向结构的指针),'&'是指向该符号的指针。

你可能也想声明如下:

struct citizen *pSpouse; 

离开“结构”作为隐含的支持C++,但不是在C(不过,如果你有一个纯C++编译器,那么你可以大多数情况下它用于C代码,这种奇怪的事情就像没有报告它应该是一个错误)。

增加:

为了测试记录0和1是否已婚:

if(People[0].pSpouse == &People[1]) 
{ 
    printf("They're married!\n"); 
} 

比较指针的值总是以检查它们是否指向同一件事的一种有效方式。

1
People[0].pSpouse = &People[1]; 
People[0].iYearOfMarriage = 2009; 

People[1].pSpouse = &People[0]; 
People[1].iYearOfMarriage = 2009; 
1

正如之前指出: 1>如果使用C编译器使用 typedef结构公民{ ... }公民;

And allPeople [0] .spouse = & allPeople [1];

allPeople [1] .spouse = & allPeople [0];