问题描述
解决方案
#include <stdlib.h>
#include <stdio.h>
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;
}
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;
}
int main()
{
Student s;
s.math = 100;
printf("%dn", s.math);
SetZero(s);
printf("%dn", s.math);
s.math = 100;
printf("%dn", s.math);
s = *SetZero1(s);
printf("%dn", s.math);
return 0;
}
100
0
100
0
解决方案二:
楼上malloc申请的内存没有释放,在使用时请千万注意内存泄漏问题!!!
解决方案三:
你直接memset(&s,0,sizeof(s));或者给student类写个方法
void setZero()
{
s.math = 0;
s.eng = 0;
s.db = 0;
}
时间: 2024-10-29 10:43:51