zoukankan      html  css  js  c++  java
  • [C]结构Struct与指针,函数

     指针传递,不返回值

    #include <stdio.h>
    #include <string.h>
    struct Student
    {
        char name[10];
        int age;
        struct subjects {
            double math;
            double english;
            double science;
        } scores;
        int grades;
    };
    
    void changeInfo(struct Student * p);
    void displayInfo(struct Student s);
    
    int main()
    {
        struct Student stuA = {"jerry", 17, {98, 97.5, 96}, 7}; //一次性全部赋值,如果缺少,会有默认值,char *对应null, int, double为0
        displayInfo(stuA);
        changeInfo(&stuA); //使用指针,传递地址
        puts("after changing info: ");
        displayInfo(stuA);
        return 0;
    }
    
    void changeInfo(struct Student * p)
    {
        strcpy(p->name, "George");
        p->age = 45;
        p->grades = 14;
        p->scores.math = 56;
        p->scores.english = 45.5;
        p->scores.science = 56.5;
    }
    
    void displayInfo(struct Student s)
    {
        printf("My name is %s, I'm %d years old and in Grade %d. I got %f %f %f in math, english, science respectively.
    ", s.name, s.age, s.grades, s.scores.math, s.scores.english, s.scores.science);
    }

    返回struct:

    #include <stdio.h>
    #include <string.h>
    struct Student
    {
        char name[10];
        int age;
        struct subjects {
            double math;
            double english;
            double science;
        } scores;
        int grades;
    };
    
    struct Student changeInfo(struct Student * p);
    void displayInfo(struct Student s);
    
    int main()
    {
        struct Student stuA = {"jerry", 17, {98, 97.5, 96}, 7}; //一次性全部赋值,如果缺少,会有默认值,char *对应null, int, double为0
        displayInfo(stuA);
        puts("
    after changing info: ");
        displayInfo(changeInfo(&stuA));
        return 0;
    }
    
    struct Student changeInfo(struct Student * p)
    {
        strcpy(p->name, "George");
        p->age = 45;
        p->grades = 14;
        p->scores.math = 56;
        p->scores.english = 45.5;
        p->scores.science = 56.5;
        return *p;
    }
    
    void displayInfo(struct Student s)
    {
        printf("My name is %s, I'm %d years old and in Grade %d. I got %f %f %f in math, english, science respectively.
    ", s.name, s.age, s.grades, s.scores.math, s.scores.english, s.scores.science);
    }

    注:

    上面的:

    #include <string.h>
    char name[10];
    strcpy(p->name, "George");

    可以换成:

    指针形式,就不需要用到string.h中的strcpy了

    char * name;
    p->name = George
  • 相关阅读:
    js简单工厂
    对象数组深浅拷贝
    分时函数的通用实现
    SQL技术内幕-4 row_number() over( partition by XX order by XX)的用法(区别于group by 和order by)
    SQL技术内幕-2
    SQL技术内幕-1
    js 阻止冒泡 兼容性方法
    C# 给数据库传入当前时间
    Ms sql server sql优化技巧
    SQl 字段中出现某一个词语的次数
  • 原文地址:https://www.cnblogs.com/profesor/p/13109841.html
Copyright © 2011-2022 走看看