[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.\n", 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("\nafter 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.\n", 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

 

posted @ 2020-06-12 19:53  profesor  阅读(331)  评论(0编辑  收藏  举报