下面的memcpy是如何超越C中的数组的?
我有以下代码:下面的memcpy是如何超越C中的数组的?,c,arrays,struct,memcpy,C,Arrays,Struct,Memcpy,我有以下代码: #define NUM_STUDENTS 20 #define TIME_STUDENTS 10 typedef struct { int name; int age; } Student; typedef struct { int number; int post; } Contact; typedef struct { int number; Student students
#define NUM_STUDENTS 20
#define TIME_STUDENTS 10
typedef struct
{
int name;
int age;
} Student;
typedef struct
{
int number;
int post;
} Contact;
typedef struct
{
int number;
Student students[TIME_STUDENTS][NUM_STUDENTS];
Contact contact[NUM_STUDENTS];
} Master;
typedef struct
{
int number;
Student students[NUM_STUDENTS][NUM_STUDENTS];
Contact contact[NUM_STUDENTS];
} Info;
Info info;
Master master;
//fill the data for master
if(NUM_STUDENTS < 10)
{
memcpy(&info.student[0][0],
&master.student[0][0],
sizeof(Student) * NUM_STUDENTS * NUM_STUDENTS);
}
问题是什么以及如何解决?在
Master
中,您只有
Student students[TIME_STUDENTS][NUM_STUDENTS];
而且TIME\u STUDENTS
小于NUM\u STUDENTS
,所以
memcpy(&info.student[0][0],
&master.student[0][0],
sizeof(Student) * NUM_STUDENTS * NUM_STUDENTS);
复制的字节数超过源的字节数。在
主控
中,您只有
Student students[TIME_STUDENTS][NUM_STUDENTS];
而且TIME\u STUDENTS
小于NUM\u STUDENTS
,所以
memcpy(&info.student[0][0],
&master.student[0][0],
sizeof(Student) * NUM_STUDENTS * NUM_STUDENTS);
复制的字节数比源的字节数多。看起来像是打字错误此
sizeof(Student)*NUM_STUDENTS*NUM_STUDENTS
应该是sizeof(Student)*TIME_STUDENTS*NUM_STUDENTS
应该是sizeof(Student)*时间学生*数量学生
那么如何解决?如果#define NUM_STUDENTS 20,那么我可以将代码更改为sizeof(Student)*NUM_STUDENTS*NUM_STUDENTS,但是如果是#define NUM_STUDENTS 5,那么代码应该是sizeof(Student)*NUM u STUDENTS*NUM_STUDENTS,如何修复这两种情况?如何修复取决于代码应该做什么。您可以memcpy(&info.students,&master.students,sizeof info.students
将尽可能多的master.students
数组复制到info.students
数组中。或者,您可以通过更改其中一个结构的定义来确保两个数组的大小相同(但是,为什么会有两种不同的类型呢?)。还有更多的选择,但在不知道预期的语义是什么的情况下,我猜不出正确的方法是什么。memcpy是什么(&info.students,&master.students,sizeof info.studentsmin\u size=min(sizeof info.students,sizeof master.students)代码>与#定义最小(a,b)((a)<(b)?(a):(b)
,因此内存(&info.students,&master.students,最小大小)如果master.students
不大于info.students
,则code>会将所有master.students
复制到info.students
中,如果master.students
大于info.students
,则复制到info.students中。那么如何修复?如果#define NUM_STUDENTS 20,那么我可以将代码更改为sizeof(Student)*NUM_STUDENTS*NUM_STUDENTS,但是如果是#define NUM_STUDENTS 5,那么代码应该是sizeof(Student)*NUM u STUDENTS*NUM_STUDENTS,如何修复这两种情况?如何修复取决于代码应该做什么。您可以memcpy(&info.students,&master.students,sizeof info.students
将尽可能多的master.students
数组复制到info.students
数组中。或者,您可以通过更改其中一个结构的定义来确保两个数组的大小相同(但是,为什么会有两种不同的类型呢?)。还有更多的选择,但在不知道预期的语义是什么的情况下,我猜不出正确的方法是什么。memcpy是什么(&info.students,&master.students,sizeof info.studentssizeof info.students
选择两种尺寸中较小的一种,也许我应该把它分开,min\u size=min(sizeof info.students,sizeof master.students)代码>与#定义最小(a,b)((a)<(b)?(a):(b)
,因此内存(&info.students,&master.students,最小大小)如果master.students
不大于info.students
,则code>将所有master.students
复制到info.students
中,如果master.students
大于info.students
,则尽可能多。