typedef struct {
char name[20];
int math;
int eng;
int db;
} Student;
void SetZero(Student& s) {
s.math = 0;
s.eng = 0;
s.db = 0;
// name 可用 memset 或 strcpy
}
呼叫:SetZero(s); 直接修改原物件,效率高且語意清晰。
Student* SetZero1(Student s) {
Student *p = (Student*)malloc(sizeof(Student));
memcpy(p, &s, sizeof(Student));
p->math = 0;
p->eng = 0;
p->db = 0;
return p; // 呼叫端需 free
}
呼叫:s = *SetZero1(s); 需手動管理記憶體,易洩漏,僅供理解指標操作。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
Student s;
s.math = 100;
printf("%d\n", s.math); // 100
SetZero(s);
printf("%d\n", s.math); // 0
s.math = 100;
printf("%d\n", s.math); // 100
s = *SetZero1(s);
printf("%d\n", s.math); // 0
return 0;
}
void reset() 或建構子預設初始化。void Student_init(Student* s) 與 void Student_reset(Student* s)。