簡體   English   中英

如何在 c 中將結構變量作為參數傳遞

[英]How to pass a struct variable as an argument in c

我正在嘗試將結構變量作為參數傳遞給 function。 但我在 function 調用 Display_Info (person);時不斷出錯 .

我搜索了類似的問題,我得到的解決方案仍然不起作用,我真的不明白為什么這段代碼沒有編譯。 我嘗試的解決方案之一來自https://fresh2refresh.com/c-programming/c-passing-struct-to-function/ ,正如您所看到的,我已經做到了,但它仍然沒有編譯。 請問我需要幫助。

#include <stdio.h>

struct HealthProfile
{
    char first_name[15];
    char last_name[15];
    char gender[15];
    int date_of_birth[3];
    float height;
    float weight;
};

typedef struct HealthProfile Person;

Person Set_Data();              //prototype to get information
void Display_Info(Person person); //prototype to display personal information
int Get_Age(int year);                          //prototype to get age
void Heart_Rate(int age);                       //protorype to calculate heart rate
void BMI(float ht, float wt);                   //prototype to get Body Mass Index

int main()
{
    Person person; //create object

    person = Set_Data(); //assign data to person object

    Display_Info(person);

    Heart_Rate(Get_Age(person.date_of_birth[2]));

    BMI(person.height, person.weight);

    return 0;
}

Person Set_Data() //Function to recieve data
{
    Person data;

    printf("\n\n*****ENTER INFO*****\n");
    printf("First Name: ");
    scanf("%s", data.first_name);
    printf("Last Name: ");
    scanf("%s", data.last_name);
    printf("Gender: ");
    scanf("%s", data.gender);
    printf("Month of birth(in num): ");
    scanf("%d", &data.date_of_birth[0]);
    printf("Day of birth(in num): ");
    scanf("%d", &data.date_of_birth[1]);
    printf("Year of birth(in num): ");
    scanf("%d", &data.date_of_birth[2]);
    printf("Height(in meters): ");
    scanf("%f", &data.height);
    printf("Weight(in kilograms): ");
    scanf("%f", &data.weight);

    return data;
}

void Display_Info(Person person)
{
    printf("\n\n*****PERSONAL INFO*****\n");
    printf("First name: %s", person.first_name);
    printf("Last name: %s", person.last_name);
    printf("Gender: %s", person.gender);
    printf("Date of birth: %d/ %d/ %d",
           person.date_of_birth[0],
           person.date_of_birth[1],
           person.date_of_birth[2]);
    printf("Age: %d", Get_Age(person.date_of_birth[2]));
    printf("Height: %.1f", person.height);
    printf("Weight: %.1f", person.weight);
}

我的編譯器甚至沒有錯誤消息,它只是無法編譯。 但是如果我注釋掉 function 調用 Display_Info (person); 代碼編譯。

您只需將其傳遞給指定結構作為參數類型:

void functionWithStructInput(Person inputPerson) {
    //...
}

您還打錯了字,您將 function 定義為Displsy_Info並嘗試將其稱為Display_Info

暫無
暫無

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

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