代码之家  ›  专栏  ›  技术社区  ›  shaila

如何在C中通过在主函数中具有结构的自定义函数?

  •  -1
  • shaila  · 技术社区  · 4 年前

    在C中,如何将具有结构的用户定义函数“add()”传递给main()函数?

    #include<stdio.h>
    struct student
    {
        char *name;
        int age;
        float per;
    };
    void add(){
        struct student o,o2;
    }
    int main()
    {
        // struct student o,o2;
        add();
        o.name="Jay";
        o.age=30;
        o.per=85.5;
        o2.name="Shine";
        o2.age=22;
        o2.per=99;
        printf("\nName        : %s",o.name);
        printf("\nAge         : %d",o.age);
        printf("\nPercent     : %f",o.per);
        printf("\n--------------------------------\n");
        printf("\nName        : %s",o2.name);
        printf("\nAge         : %d",o2.age);
        printf("\nPercent     : %f",o2.per);
     
        return 0;
    }
    

    如果执行上述程序,就会抛出错误。但是我们在add()中声明了这个结构。那么,如果我们调用外接程序main函数,它应该运行struct,对吗?为什么会抛出错误?

    1型和2型之间有什么区别;2型? 1型

    void add(){
        struct student o,o2;
    }
    

    2型

    void add(struct student o,o2);
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Peaky_001    4 年前
    #include<stdio.h>
    void add();
    struct student
    {
        char *name;
        int age;
        float per;
    };
    struct student o,o2;
    void add(){
        struct student o,o2;
    }
    int main()
    {
    
        // struct student o,o2;
        add();
        o.name="Jay";
        o.age=30;
        o.per=85.5;
        o2.name="Shine";
        o2.age=22;
        o2.per=99;
        printf("\nName        : %s",o.name);
        printf("\nAge         : %d",o.age);
        printf("\nPercent     : %f",o.per);
        printf("\n--------------------------------\n");
        printf("\nName        : %s",o2.name);
        printf("\nAge         : %d",o2.age);
        printf("\nPercent     : %f",o2.per);
     
        return 0;
    }
    

    output:-

    Name        : Jay
    Age         : 30
    Percent     : 85.500000
    --------------------------------
    
    Name        : Shine
    Age         : 22
    Percent     : 99.000000
    

    1.你没有申报 void add() 作用

    1. 你忘了申报 struct student o,o2 全球地。

    type1:-

    void add(){
        struct student o,o2;
    }
    

    在将结构传递给函数之前,此函数不会执行任何操作。比如type2。

    type2:-

       void add(struct student o,o2);
    

    在这种情况下,整个结构通过值传递给另一个函数。这意味着整个结构与所有成员及其值一起传递给另一个函数。所以,这个结构可以从被调用的函数中访问。这个概念在用C编写大型程序时非常有用。