简体   繁体   English

使用memcpy将结构的动态数组的内容复制到另一个动态数组中

[英]copying the content of an dynamic array of structs into another dynamic array using memcpy

I want to copy the content of a dynamic array containing 2 structs to another dynamic array of the same size. 我想将包含2个结构的动态数组的内容复制到另一个相同大小的动态数组。

I need an exact copy. 我需要一个精确的副本。 When I compile, I get these 2 errors at the last line: 编译时,在最后一行得到以下两个错误:

invalid use of undefined type 'struct student' & dereferencing pointer to incomplete type 无效使用未定义类型'struct student'取消引用不完整类型的指针

I don't understand these 2 errors. 我不明白这两个错误。

Here is my code: 这是我的代码:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct Movie{
    char name [7];
    int price;
    int year;
};

int main(int argc, char ** argv){

     struct Movie m1,m2;
     strcpy(m1.name,"Rambo");
     m1.price=20;
     m1.year=1980;

     strcpy(m2.name,"universal soldier");
     m2.price=30;
     m2.year=1990;

     struct Movie * db= malloc(2*sizeof(struct Movie));
     *db=m1;
     *(db+1)=m2;

     int i;
     for(i=0;i<2;i++){
         printf("%s\n",(*(db+i)).name);
     }

     struct student * db_copy= malloc(2*sizeof(struct Movie));
     memcpy(&db_copy,&db,sizeof(db));
     for(i=0;i<2;i++){
         printf("%s\n",(*(db_copy+i)).name); //here occur the two errors
     }
}   

You need to let the compiler know what struct student is, and that's nowhere in the code. 您需要让编译器知道struct student是什么,而这在代码中就不存在。

The errors mean: 错误的意思是:

  1. invalid use of undefined type 'struct student': You're using an undefined type 无效使用未定义类型'struct student':您正在使用未定义类型
  2. dereferencing pointer to incomplete type: You're dereferencing (accessing actual value / structure) of an incomplete type, since the definition of the type is missing. 取消引用不完整类型的指针:您正在取消引用(访问实际值/结构)不完整类型,因为缺少类型定义。

I guess the real problem though is that you meant to write: 我想真正的问题是您打算写:

struct Movie * db_copy= malloc(2*sizeof(struct Movie));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM