Search code examples
carraysstructmemcpy

how the following memcpy is beyond array in C?


I have the following code:

#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);
}

the NUM_STUDENTS can be modify from 1 to 20. but I got the following warnings:

Warning 420: Apparent access beyond array for function 'memcpy(void *, const void *, unsigned int)', argument 3 exceeds argument 2

what is the problem and how to fix it?


Solution

  • In Master, you have only

    Student         students[TIME_STUDENTS][NUM_STUDENTS];
    

    and TIME_STUDENTS is smaller than NUM_STUDENTS, so

     memcpy(&info.student[0][0],
           &master.student[0][0],
           sizeof(Student) * NUM_STUDENTS * NUM_STUDENTS);
    

    copies more bytes than the source has.