指针传递,不返回值
#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