C中的结构内部结构

时间:2014-02-21 15:11:42

标签: c struct

我正在学习C并且相对较新。

我遇到了Structs的问题,我正在尝试获取一个结构变量来保存值firstNamelastNametrieswon和{{1 }}。最后三个本身必须包含在第一个结构中的另一个结构中。我的代码如下,如果有人能解释结构标签和变量类型之间的差异,这将有很大帮助。我知道代码中可能存在很多错误。

percentage

4 个答案:

答案 0 :(得分:3)

访问struct里面的struct时,请这样做:

player.record.tries = 16;
player.record.won = 14;
player.record.percentage = (((float)player.record.won/player.record.tries)*100);

对于结构标记,struct team类型,team是结构标记,而struct team一起构成类型。您可以使用typedef来使用不带struct关键字的结构类型。

typedef struct team team;

答案 1 :(得分:1)

您知道如何访问结构成员(例如player.firstname),访问嵌套结构成员是相同的,使用“点”成员选择运算符:

player.record.tries = ...;

答案 2 :(得分:0)

编译器应发出错误,因为您定义了具有不同类型的同名玩家

struct team player;                             //Assign variable name and test print to check that 
// ...
struct stats player;

你应该写

struct team player;                             //Assign variable name and test print to check that struct is working.
strcpy(player.firstName,"Michael");
strcpy(player.lastName,"Jordan");

player.record.tries = 16;
player.record.won = 14;
player.record.percentage = ((player.record.won / player.record.tries)*100);

或者你可以写

int main(){
  //Assign variable name and test print to check that struct is working.
  struct team player;
  strcpy(player.firstName,"Michael");
  strcpy(player.lastName,"Jordan");

  struct stats s;
  s.tries = 16;
  s.won = 14;
  s.percentage = ((s.won/s.tries)*100);

  player.record = s;
  // ,,,

答案 3 :(得分:0)

您还可以通过struct保存typedef到处输入的内容。有关详情,请参阅此question and accepted answer

相关问题