簡體   English   中英

C中的內部結構

[英]Structure inside structure in C

我正在學習C並相對較新。

我在使用Structs時遇到麻煩,並且嘗試獲取一個結構變量來保存值firstNamelastNametrieswonpercentage 最后三個本身必須包含在第一個結構中的另一個結構中。 我的代碼在下面,如果有人能解釋結構標簽和變量類型之間的區別也有很大幫助。 我了解代碼中可能存在很多錯誤。

#include <stdio.h>
#include <string.h>

struct team{
    char firstName[40];                     
    char lastName[40];

    struct stats{
        int tries;

        int won;

        float percentage;
    } record;
}; 

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 player;
  player.tries = 16;
  player.won = 14;
  player.percentage = ((player.won/player.tries)*100);

  printf("First Name: \t %s \n", player.firstName);
  printf("Last Name: \t %s \n", player.lastName);
  printf("Tries: \t %d \n", player.tries);
  printf("Won: \t %d \n", player.won);
  printf("Percentage: \t %f \n", player.percentage);

  return 0;
}

當訪問struct內部的struct時,請執行以下操作:

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

至於struct標記,對於struct team類型, team是struct標記,而struct team共同構成一個類型。 您可以使用typedef來使用不帶struct關鍵字的struct類型。

typedef struct team team;

您知道如何訪問結構成員(例如player.firstname ),使用“點”成員選擇運算符訪問嵌套的結構成員是相同的:

player.record.tries = ...;

編譯器將發出錯誤,因為您定義了具有不同類型的相同名稱播放器

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;
  // ,,,

您還可以節省打字struct處處typedef荷蘭國際集團它。 有關更多信息,請參見此問題和已接受的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM