c - 以下 memcpy 如何超出 C 中的数组?

标签 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[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);
}

NUM_STUDENTS 可以从 1 修改为 20。 但我收到以下警告:

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

问题是什么以及如何解决?

最佳答案

Master中,你只有

Student         students[TIME_STUDENTS][NUM_STUDENTS];

并且 TIME_STUDENTS 小于 NUM_STUDENTS,所以

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

复制比源更多的字节。

关于c - 以下 memcpy 如何超出 C 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17112698/

相关文章:

php - 在 php 中按键比较多维数组值

php - 多维 array_values 仅适用于整数键

c - 如何改变C中数组的大小?

c - 在 C99 中强制结构体中枚举值的宽度

c - 如何在客户端应用程序中使用 "control endpoint"(默认端点)?

c - C 中的简单减法代码没有答案

c - 如何将通用结构传递给 C 中的函数?

c - 在 C 中另存为二进制文件,但不显示零和一

c++ - 让宏定义为函数返回一个值是不好的做法吗?

c - scanf 上的段错误并非在所有系统上都存在